Promise

57 阅读1分钟

1、Promise是JavaScript中进行异步编程的新的解决方案
2、从语法上看:Promise是一个构造函数
3、从功能上看:Promise对象用来封装一个异步操作并可以获取其结果

1、pending →  resolved
2、pending →  rejected
一个Promise对象只能改变一次,无论成功还是失败,都只有一个结果数据

image.png

  // 创建一个Promise对象
  const p = new Promise((resolve, reject) => { // 执行器函数 同步函数
    console.log('执行executor');
    // 执行异步操作
    setTimeout(() => {
      const randomNum = Math.floor(Math.random() * 10);
      // 0-9的随机数是偶数代表成功,否则代表失败
      if (randomNum % 2 === 0) {
        // 成功,调用resolve(value)
        resolve('成功' + randomNum)
      } else {
        // 失败,调用reject(reason)
        reject('失败' + randomNum)
      }
    }, 500)
  })
  console.log('new Promise()之后');
  p.then(
    value => {
      console.log('成功的回调onResolved', value);
    },
    reason => {
      console.log('失败的回调onRejected', reason);
    }
  )

image.png

image.png

      setTimeout(() => {
        reject('失败的数据')
      }, 500)
    }).then(
      value => {
        console.log('onResolved()1' + value); 
      }
    ).catch(
      reason => {
        console.log('onRejected()1' + reason); // onRejected()1失败的数据
      }
    )

image.png

image.png

image.png

image.png

来源