promise使用

87 阅读1分钟

1, resolve的使用


    function async1 () {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('async1');
          resolve('async1完成')
        }, 1000);
      })
    }

    function async2 () {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('async2');
          resolve('async2完成')
        }, 2000);
      })
    }

    function async3 () {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('async3');
          resolve('async3完成')
        }, 3000);
      })
    }

    async1()
      .then(function (data) {
        console.log('data1', data);
        return async2();
      })
      .then(function (data) {
        console.log('data2', data);
        return '直接返回数据';  //这里直接返回数据
      })
      .then(function (data) {
        console.log('data3', data);
      });

2, all使用

// all的使用
  Promise.all([async1(), async2(), async3()]).then((result) => {
      console.log(result);
      // do something...
    }).catch((err) => {
      console.log(err);
    });