zoukankan      html  css  js  c++  java
  • ES6中的Promise

    Promise

    Promise 翻译过来就是承诺的意思,这个承诺会在未来有一个确切的答复,并且该承诺有三种状态,这个承诺一旦从等待状态变成为其他状态就永远不能更改状态了。

    • 等待中(pending)
    • 完成了(resolved)更准确的应该说是(fulfilled)
    • 拒绝了(rejected)

    当我们在构造 Promise 的时候,构造函数内部的代码是立即执行的。

    new Promise((resolve, reject) => {
      console.log('new Promise')
      resolve('success')
    })
    console.log('finifsh')
    
    // 先打印new Promise, 再打印 finifsh
    

    Promise 实现了链式调用,也就是说每次调用 then 之后返回的都是一个 Promise,并且是一个全新的 Promise,原因也是因为状态不可变。如果你在 then 中 使用了 return,那么 return 的值会被 Promise.resolve() 包装。

    Promise.resolve(1)
      .then(res => {
        console.log(res) // => 1
        return 2 // 包装成 Promise.resolve(2)
      })
      .then(res => {
        console.log(res) // => 2
      })
    

    当然了,Promise 也很好地解决了回调地狱的问题

    ajax(url)
      .then(res => {
          console.log(res)
          return ajax(url1)
      }).then(res => {
          console.log(res)
          return ajax(url2)
      }).then(res => console.log(res))
    

    其实它也是存在一些缺点的,比如无法取消 Promise,错误需要通过回调函数捕获。

    今天你学习了吗!!!
  • 相关阅读:
    js 数组方法比较
    js 知识点
    vuex、redux、mobx 对比
    读SRE Google运维解密有感(二)
    读SRE Google运维解密有感(一)
    001_深度剖析什么是 SLI、SLO和SLA?
    006_mac osx 应用跨屏幕
    005_ss-link.info的ping探测工具
    015_sublime插件管理及所有非常有用插件
    001_软件waf
  • 原文地址:https://www.cnblogs.com/nayek/p/11728855.html
Copyright © 2011-2022 走看看