Promise 的三种状态

  • Pending 进行中
  • Fulfilled 已成功
  • Rejected 已失败

状态转变

Promise对象的状态,只有两种情况:

  • Pending 变为 Fulfilled
  • Pending 变为 Rejected

javascript-promise-book@www.jb51.jpg

基本用法

  1. // 返回一个 promise 对象
  2. const createPromise = () => {
  3. return new Promise((resolve, reject) => {
  4. // some code...
  5. if (false) {
  6. resolve()
  7. } else {
  8. reject()
  9. }
  10. })
  11. }
  12. // promise 对象内部执行 resolve() 时,会执行该函数
  13. // resolve() 的参数传给该函数
  14. const onFulfilled = () => {
  15. console.log('成功')
  16. }
  17. // promise 对象内部执行 reject() 时,会执行该函数
  18. // reject() 的参数传给该函数
  19. const onRejected = () => {
  20. console.log('失败')
  21. }
  22. let promiseObj = createPromise()
  23. // <= 关键: 设置resolve()和reject() 时执行的函数
  24. promiseObj.then(onFulfilled, onRejected)
  1. let promiseObj = createPromise()
  2. // 也可以使用 .catch() 方法代替 .then(null, onRejected)
  3. promiseObj
  4. .then(onFulfilled)
  5. .catch(onRejected)

2.jpg

简单的例子

  1. // 间隔一段时间后执行
  2. const timeout = (ms, str) => {
  3. return new Promise((resolve, reject) => {
  4. setTimeout(resolve, ms, str) // str 作为 resolve函数的参数
  5. })
  6. }
  7. let timeOutPromise = timeout(1000, 'hello promise')
  8. timeOutPromise.then((str) => {
  9. console.log('then:' + str)
  10. })
  11. // 100ms后输出
  12. // then:hello promise

Promise 新建后立即执行

  1. // Promise 对象创建后立即执行
  2. let promiseObj = new Promise((resolve, reject) => {
  3. console.log('inner log') // <= 1
  4. resolve()
  5. })
  6. promiseObj.then(()=>{
  7. console.log('then log') // <=3
  8. })
  9. console.log('outer log') // <=2

一个异步操作的结果是返回另一个异步操作

  1. let p1 = new Promise((resolve, reject) => {
  2. setTimeout(()=>reject(new Error('p1 fail')), 3000) // 3 秒后执行
  3. })
  4. let p2 = new Promise((resolve, reject) => {
  5. setTimeout(() => resolve(p1), 1000) // <= resolve的参数为另一个 promise对象且处于Pending状态
  6. })
  7. p2
  8. .then(result => console.log(result))
  9. .catch(error => console.log(error.toString()))
  10. // 3秒后输出
  11. // Error: p1 fail

上面的例子中,p2 的 resolve() 方法把 p1 作为参数,此时 p1 的状态就会传递给 p2。
也就是说,p1 的状态决定了 p2 的状态。如果 p1 的状态是 Pending,那么 p2的回调函数就会等待 p1 的状态改变,如果 p1 的状态已经是 Resolved 或 Rejected,那么 p2 的回调函数将会立刻执行。

  1. let p1 = new Promise((resolve, reject) => {
  2. setTimeout(()=>reject(new Error('p1 fail')), 1000) // 1 秒后执行
  3. })
  4. let p2 = new Promise((resolve, reject) => {
  5. setTimeout(() => resolve(p1), 2000) // 2 秒后执行,执行时 p1 处于 Rejected 状态
  6. })
  7. p2
  8. .then(result => console.log('p2 then', result))
  9. .catch(error => console.log('catch', error.toString()))
  10. // 输出
  11. (node:9620) UnhandledPromiseRejectionWarning: Error: p1 fail
  12. at Timeout.setTimeout [as _onTimeout] (E:\AllCode\Code\html+css+js\23_promise小书\src\06.pro
  13. mise.js:2:25) <= 2行的reject(),没有处理 onRejected 函数
  14. at ontimeout (timers.js:436:11)
  15. at tryOnTimeout (timers.js:300:5)
  16. at listOnTimeout (timers.js:263:5)
  17. at Timer.processTimers (timers.js:223:10)
  18. (node:9620) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated
  19. either by throwing inside of an async function without a catch block, or by rejecting a promise
  20. which was not handled with .catch(). (rejection id: 1)
  21. (node:9620) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the fu
  22. ture, promise rejections that are not handled will terminate the Node.js process with a non-zero
  23. exit code.
  24. catch Error: p1 fail <= 执行 catch 语句
  25. (node:9620) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (reject
  26. ion id: 1)
  1. let p1 = new Promise((resolve, reject) => {
  2. setTimeout(()=>resolve(new Error('p1 fail')), 1000) // 1 秒后执行,p1 状态为 Resolved
  3. })
  4. let p2 = new Promise((resolve, reject) => {
  5. setTimeout(() => resolve(p1), 2000) // 此时 p1 的状态为 Resolved,立即执行 .then 回调
  6. })
  7. p2
  8. .then(result => console.log('p2 then', result.toString())) // result 为 p1的resolve参数, error 对象
  9. .catch(error => console.log('catch', error.toString()))

Promise.prototype.then()

Promise.prototype.catch()

Promise.all()

Promise.race()

Promise.resolve()

Promise.reject()

附加方法

done()

finally()