gpt4 book ai didi

javascript - 运行 3 个 Promise,然后在其他 Promise 完成后运行最后一个 Promise

转载 作者:太空宇宙 更新时间:2023-11-04 03:04:54 25 4
gpt4 key购买 nike

我正在编写一个 Nodejs Controller 。

我有一整套 promise ,其中每个 promise 都从不同的查询中获取数据

我想启动它们(因为它们需要不同的时间来完成),一旦它们全部完成,我想启动我的priceCalc函数,它使用收集到的所有数据。

我查看了很多指南和示例,但我不明白 Promise.all 以及它如何在我的案例中发挥作用?

此外,如果其中一个失败,它应该返回错误怎么办?它们必须全部完成,priceCalc 函数才能启动。

(我是 Promise 的新手,所以如果可以的话请让它变得简单:-)))

var findPrice = new Promise(
(resolve, reject) => {
priceTable.findOne........

var movePrice = function (data) {
priceArray = data......

findPrice
.then(movePrice)
.then(fulfilled => console.log('findPrice FINISHED!!!'))
.catch(error => console.log(error.message));


var findhotdeal = new Promise(
(resolve, reject) => {
hotdealTable.aggregate.........

var movehotdeal = function (data) {
hotdealArray = data;.......

findhotdeal
.then(movehotdeal)
.then(fulfilled => console.log('findhotdeal FINISHED!!!'))
.catch(error => console.log(error.message));


var calculatePrice = function () {
// Use the data from the previous promises once they all finished

}

最佳答案

如果您需要所有 4 个 Promise 的解析值

var findPrice = new Promise(
(resolve, reject) => {
priceTable.findOne........

var movePrice = function (data) {
priceArray = data......

var findhotdeal = new Promise(
(resolve, reject) => {
hotdealTable.aggregate.........

var movehotdeal = function (data) {
hotdealArray = data;.......

var calculatePrice = function ([fp, mp, fh, mh]) {
// fp == resolved value of findPrice
// mp == resolved value of movePrice
// fh == resolved value of findhotdeal
// mh == resolved value of movehotdeal
}

Promise.all([findPrice, findPrice.then(movePrice), findhotdeal, findhotdeal.then(movehotdeal)])
.then(calculatePrice)
.catch(err => { /* handle errors here */})

注意:

var calculatePrice = function ([fp, mp, fh, mh]) {
// fp == resolved value of findPrice
// mp == resolved value of movePrice
// fh == resolved value of findhotdeal
// mh == resolved value of movehotdeal
}

是 ES2015+ 的简写

var calculatePrice = function (r) {
var fp = r[0],
mp = r[1],
fh = r[2],
mh = r[3];

// fp == resolved value of findPrice
// mp == resolved value of movePrice
// fh == resolved value of findhotdeal
// mh == resolved value of movehotdeal
}

Given that movePrice and movehotdeal are not asyncrhonous

var findPrice = new Promise((resolve, reject) => {
priceTable.findOne........
});

var findhotdeal = new Promise((resolve, reject) => {
hotdealTable.aggregate.........
});

var calculatePrice = function ([fp, fh]) {
priceArray = fp;
hotdealArray = fh;
// fp == resolved value of findPrice
// fh == resolved value of findhotdeal
}

Promise.all([findPrice, findhotdeal])
.then(calculatePrice)
.catch(err => { /* handle errors here */})

关于javascript - 运行 3 个 Promise,然后在其他 Promise 完成后运行最后一个 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43930247/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com