如何在使用 promise 时分别 运行 多个函数?

how to run multiple functions respectively while using promises?

我正在尝试按顺序 运行 4 个函数,我已经尝试了下面的代码,但有些函数在 运行 执行第一个和第二个函数后卡住了

代码示例:

const Bluebird = require('bluebird');

///// also tried changing all Bluebird below to Promise -> didn't work

//const Promise = require('bluebird');

const promisesFunc = async (array) => {
    let interval = 1000;
    const delayPromise1 = (data, delayDuration) => {
      return new Promise((resolve) => {
        setTimeout(() => {
            /// do some code here requires .map function may take 10s or more
            resolve();
        }, delayDuration)
      });
    };

    const delayPromise2 = (data, delayDuration) => {
      return new Promise((resolve) => {
        setTimeout(() => {
            /// do some code here requires .map function may take 10s or more
            resolve();
        }, delayDuration)
      });
    };

    const delayPromise3 = (data, delayDuration) => {
      return new Promise((resolve) => {
        setTimeout(() => {
            /// do some code here requires .map function may take 10s or more
            resolve();
        }, delayDuration)
      });
    };

    const delayPromise4 = (data, delayDuration) => {
      return new Promise((resolve) => {
        setTimeout(() => {
            /// do some code here requires .map function may take 10s or more
            resolve();
        }, delayDuration)
      });
    };

    try {
    /////////////// first attempt //////////////
    await Bluebird.map(array, (data, index) => delayPromise1(data, index * interval))
    await Bluebird.map(array, (data, index) => delayPromise2(data, index * interval))
    await Bluebird.map(array, (data, index) => delayPromise3(data, index * interval))
    await Bluebird.map(array, (data, index) => delayPromise4(data, index * interval))
    console.log('done ***************************************************');
    setTimeout(() => {
      console.log('response was sent');
      res.status(200).json('done')
    }, 1000);

    /////////////// second attempt ////////////

    const promises = Bluebird.map(array, (data, index) => delayPromise1(data, index * interval))
      .then(() => Bluebird.map(array, (data, index) => delayPromise2(data, index * interval)))
      .then(() => Bluebird.map(array, (data, index) => delayPromise3(data, index * interval)))
      .then(() => Bluebird.map(array, (data, index) => delayPromise4(data, index * interval)))
      .then(() => {
        setTimeout(() => {
          console.log('response was sent');
          res.status(200).json('done')
        }, 1000);
      })
      .catch(err => console.error(err))

      await Promise.all([promises]);

      ///////////// third attempt ////////////////////

      const promises1 = array.map((data, index) => delayPromise1(data, index * interval));
      const promises2 = array.map((data, index) => delayPromise2(data, index * interval));
      const promises3 = array.map((data, index) => delayPromise3(data, index * interval));
      const promises4 = array.map((data, index) => delayPromise4(data, index * interval));
      await Promise.all([promises1, promises2, promises3, promises4]);
      setTimeout(function(){
        console.log('response was sent');
        res.status(200).json('done')
      }, 1000);


    } catch (e) {
      console.error(e);
    }
}
promisesFunc(array)

注意 在第一次和第二次尝试中 delayPromise1 和 delayPromise2 函数 运行s 成功但随后停止并且不再继续,其他解决方案分别不起作用

知道为什么会发生这种情况,是否有更好的解决方案来分别将这些功能承诺给 运行。

PS 函数结构需要这样。他们需要运行一个接一个的顺序

在数据数组中映射,然后在 delayPromise 函数中对其进行一些处理,然后是 resolve()。在某些情况下,解决承诺不必等待代码执行完成。

你的第三次尝试是可行的。但是,您可以在 Promise.all 解析并完成所有异步操作后发送您的回复。

const promises1 = array.map((data, index) => delayPromise1(data, index * interval));
const promises2 = array.map((data, index) => delayPromise2(data, index * interval));
const promises3 = array.map((data, index) => delayPromise3(data, index * interval));
const promises4 = array.map((data, index) => delayPromise4(data, index * interval));

await Promise.all([promises1, promises2, promises3, promises4]).then(() => {
  console.log('response was sent');
  return res.status(200).json('done')
})

我会像这样使用数组 .reduce 方法:

[delayPromise1, delayPromise2, ...]
    .reduce((m, delayPromise) => {

        /* here we chain the promises */
        return Promise.resolve(m).then(delayPromise)

    }, {/* any input data to be the argument of delayPromise1 */} )

    .then( res => {

        // do something when all is ready
    })

如果你想 运行 并行传递所有延迟函数在 Promise.all 内传递。如果你想 运行 按顺序使用如下。

const promisesFunc = async (array) => {
    let interval = 1000;
    const delayPromise1 = (data, delayDuration) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                /// do some code here requires .map function may take 10s or more
                resolve();
            }, delayDuration)
        });
    };

    const delayPromise2 = (data, delayDuration) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                /// do some code here requires .map function may take 10s or more
                resolve();
            }, delayDuration)
        });
    };

    const delayPromise3 = (data, delayDuration) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                /// do some code here requires .map function may take 10s or more
                resolve();
            }, delayDuration)
        });
    };

    const delayPromise4 = (data, delayDuration) => {
        return new Promise((resolve) => {
            setTimeout(() => {
                /// do some code here requires .map function may take 10s or more
                resolve();
            }, delayDuration)
        });
    };

    try {
        console.log("START");
        await Promise.all(array.map((data, index) => delayPromise1(data, index * interval)));
        console.log("Done delayPromise1");
        await Promise.all((array.map((data, index) => delayPromise2(data, index * interval))));
        console.log("Done delayPromise2");
        await Promise.all(array.map((data, index) => delayPromise3(data, index * interval)));
        console.log("Done delayPromise3");
        await Promise.all(array.map((data, index) => delayPromise4(data, index * interval)));
        console.log("Done delayPromise4");
        console.log("DONE");
    } catch (e) {
        console.error(e);
    }
};

promisesFunc([1, 2, 3])