我有一个3个函数的数组,它们使用节点获取从3个不同的API中获取数据。如果第一个函数的response.body包含'rejected',我只想调用第二个和第三个函数。3个请求函数的数组 - 仅当第一个函数的响应包含字符串时如何调用第二个函数? - Node JS
我正在运行的问题是所有的方法在从第一个接收到响应之前被调用。
const buyersList = [
{ buyerName: 'ACME',
buyerPrice: '100',
buyerMethod: sellACME,
},
{ buyerName: 'ACME',
buyerPrice: '60',
buyerMethod: sellACME,
},
{ buyerName: 'ACME',
buyerPrice: '20',
buyerMethod: sellACME,
},
{ buyerName: 'ACME',
buyerPrice: '2',
buyerMethod: sellACME,
},
];
//fetch the data and parse
function sellACME(url) {
return fetch(url, { method: 'POST' })
.then(obj => parseResponse(obj))
.catch(err => console.log(' error', err));
}
//shift the first item in array and execute the method for first item.
const methods = {};
methods.exBuyerSell = (url) => {
const currBuyer = buyersList.shift();
return currBuyer.buyerMethod(url);
};
//loop through array.
module.exports = (url, res) => {
while (buyersList.length > 0) {
methods.exBuyerSell(url)
.then((buyerRes) => {
//if response.result is accepted, empty array, send response to client.
if (buyerRes.result === 'accepted') {
buyersList.length = 0;
res.json(buyerRes);
}
//if response.result is rejected, execute the next item in array.
if (buyerRes.result === 'rejected') {
methods.exBuyerSell(url);
}
return buyerRes;
});
}
};
业务这里逻辑是,如果该数据被发送到所述第一买方,该数据是由买方接受并不能呈现给第二买方。
setTimeout()不是一个选项,因为数组可以增长到20,每个请求最多可能需要180秒。
我试图使用async/await和async.waterfall,但似乎仍然有同样的问题。
我误解你的问题第一时间。请检查我更新的答案。希望能帮助到你。 –