如何实现 3 个功能的 Javascript 承诺?

How to implement Javascript promises for 3 functions?

我有 3 个函数,它们都需要特定的时间来执行,然后当它们全部完成时我需要触发某个函数。使用以下代码,我可以通过单个函数获得预期结果,但对于多个函数我无法做到,请帮助我编辑此代码以等待我的 3 函数然后控制台他们返回的数据。

var promise = new Promise(function(resolve, reject) 
{
    setTimeout(function() 
    {
        resolve('hello world');
    }, 2000);
});

promise.then(function(data) 
{
    console.log(data);
});

您可以参考这段代码,该函数被调用了 3 次,有两种方法可以做到这一点,您还可以看到不同的行为。

// Function which returns a promise and resolves in 2 seconds
    const promiseFunction = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve('resolved');
        }, 2000);
      });
    };

    // Asynchronous function 1
    const asyncFunction1 = async() => {
        console.log(await promiseFunction());
        console.log(await promiseFunction());
        console.log(await promiseFunction());
    }

    // Asynchronous function 2
    const asyncFunction2 = async() => {
        let a = promiseFunction();
        let b = promiseFunction();
        let c = promiseFunction();

        console.log(await a);
        console.log(await b);
        console.log(await c);
    }   

看两者的区别
asyncFunction1()asyncFunction2() 呼叫

使用 async/await 是一种 ES6 方式,您也可以进行 .then() 链接

promiseFunction().then(() => {
//function body here
})

您可以像这样链接您的承诺:

new Promise(function(resolve, reject) {
  resolve(1);
}).then(function(result) { 
  // result is 1
  return result * 2;
}).then(function(result) { 
  // result is 2
  return result * 2;
}).then(function(result) {
  // result is 4
  return result * 2;
});

要保留所有函数的结果,您可以将结果作为一个数组,并每次将新结果推送给它。像这样:

new Promise(function(resolve, reject) {
  resolve([0]);
}).then(function(result) { 
  result.push(1);
  return result;
}).then(function(result) { 
  result.push(2);
  return result;
}).then(function(result) {
  result.push(3);
  console.log(result);
  return result;
});

这将记录 [0,1,2,3]

Javascript 有一个内置方法,等待您承诺解决所有问题。

Promise.all([promise1, promise2, promise3]).then(function(values) {
  console.log(values);
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

所以对于你的情况:

const promiseFunction = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
};

const promise1 = promiseFunction();
const promise2 = promiseFunction();
const promise3 = promiseFunction();

Promise.all([promise1, promise2, promise3])
  .then((result) => {
    console.log(result[0]);
    console.log(result[1]);
    console.log(result[2]);
  })

结果是每个承诺返回的值数组。

如果 promise 相互独立,则使用 Promise.all:

Promise.all([promise1, promise2, promise3]).then(console.log);

Promise.all() 将接受一组承诺作为参数并等待所有承诺完成。

    var promise1 = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve('function 1 resolved');
    }, Math.random() * 10000);
});

var promise2 = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve('function 2 resolved');
    }, Math.random() * 10000);
});

var promise3 = new Promise(function (resolve, reject) {
    setTimeout(function () {
        resolve('function 3 resolved');
    }, Math.random() * 10000);
});

Promise.all([promise1, promise2, promise3])
    .then(resArr => {
        console.log(resArr)
    })

您可以使用附加到 promise.all()

的 .catch() 捕获任何 promise 中发生的错误
Promise.all([promise1, promise2, promise3])
    .then(resArr => {
        console.log(resArr)
    })
    .catch(error => console.log(error))