我有一个有 promise 的函数,循环遍历医院、酒店和赌博。 然后它当前正在合并并返回它。
重写此函数的最佳方法是什么,以便可以循环遍历每个 promiseArrs
结果并做一些更有希望的事情?
function GetOwnedFirms(userid) {
var promiseArr = [
hospital.find({userid: userid}),
hotel.find({owner: userid}),
gambling.find({userid: userid}),
];
return Promise.all(promiseArr).then(function (results) {
// Want to loop trough each results with a new promise etc..
// call funct1 promise to hospital, func2 to hotel, etc etc.
// then after everything is done, concat them and return.
var OwnedFirms = results[0].concat(results[1], results[2]);
return OwnedFirms;
});
}
最佳答案
如果您想遍历这些结果并执行更多操作以产生 promise ,只需这样做,并返回 Promise.all
的结果在你的 then
之外的那些操作上回调:
function GetOwnedFirms(userid) {
var promiseArr = [
hospital.find({userid: userid}),
hotel.find({owner: userid}),
gambling.find({userid: userid}),
];
return Promise.all(promiseArr).then(function(results) {
return Promise.all(results[0].concat(results[1], results[2]).map(function(firm) {
return doSomethingThatGeneratesAPromiseWith(firm);
}));
});
}
请记住, promise 链是管道,其中每个 then
或 catch
处理程序可以转换通过的结果,包括异步操作。 then
和 catch
创造新的 promise 。如果您从 then
返回一个 promise 或 catch
回调,由 then
创建的 promise 或 catch
已解决您返回的 promise (这意味着它将根据该 promise 的内容实现或拒绝)。 (有关该术语的更多信息 on my blog 如果您不熟悉其中的任何一个。)
回复你的评论:
But i have to go trough each of them seperatly, hospital will have one kind of promise, hotel another etc. How would that work ?
...
But then i wonder how i would make each of the results into another promise, and then on final ( before returning it all), combine them :) cause 0 (hospital) have to do something different from hotel. Im worrying if i make it wrong. I need to have all the results new promises done before returning them and combing them.
正如我在评论中所说,您只需将相同的原则应用于各个结果。最简单的方法是在你的 Promise.all
之前:
function GetOwnedFirms(userid) {
return Promise.all([
hospital.find({userid: userid}).then(function(hospital) {
return doSomethingAsyncWithHospital(hospital);
}),
hotel.find({owner: userid}).then(function(hotel) {
return doSomethingAsyncWithHotel(hotel);
}),
gambling.find({userid: userid}).then(function(gambling) {
return doSomethingAsyncWithGambling(gambling);
})
]).then(function(results) {
return results[0].concat(results[1], results[2]);
});
}
看看我们如何仍在使用 promise 链是管道这一事实。我们正在转换三个链中的每一个,然后在最后将它们聚集在一起(我假设您确实想要这样做;如果不是,只需删除最后的 then
处理程序)。
关于javascript - 每个 promise node.js/js 上的更多 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46488799/