廖亚军的个人博客

Logo

苟日新,日日新,又日新

术语通俗解释

介绍

概念

优点

示例

const asyncFn = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('success')
      // reject('err')
      // 异步操作中通过 throw 抛出的错误无法捕获
      // 因为 try...catch 只能捕获同步操作抛出的错误
      // throw 'err'
    }, 1000)
  })
}
asyncFn().then(
  value => {
    console.log(value)
  },
  // 实际使用中,一般在最后通过 .catch 统一捕获错误
  reason => {
    console.warn(reason)
  }
)

Promise 的 API

Promise 构造函数 new Promise(executor)

Promise 的内部属性

PromiseState(状态)

PromiseResult(结果值)

Promise 的静态方法

Promise.resolve(value)

Promise.reject(reason)

Promise.all(iterable)

Promise.race(iterable)

实例方法

Promise.prototype.then(onFulfilled, onRejected)

Promise.prototype.catch(onRejected)

Promise.prototype.finally(onFinally)

async 与 await

async 函数

await 表达式

注意事项