[英]call async function for each array element of a promise result object, make changes and return this object
蓝鸟承诺会返回一个对象,其中包含对象,汽车和合同的两个数组。 然后,我要遍历汽车,调用异步函数,然后根据返回的值对第二个数组进行一些更改,并使用这些更改返回初始结果对象。 我不知道如何用诺言做到这一点。 或与异步,为此。 我觉得它们应该是嵌套的承诺,但是我根本无法使它工作。
承诺版本:
somePromise().then(function (result) {
Promise.each(result.cars, function (car) {
makeAsyncCall(car.id, function (err, resultArray) {
if (err) {
throw new Error();
}
result.contracts.forEach(function (contract) {
if (resultArray.indexOf(contract.id) > -1) {
contract.car = car.id;
}
});
});
}).then(function (eachResult) {
//eachResult is result.firstArray, which is not interesting.
return result;
});
}).then(function (result)) {
//this gets called before my promise.each gets executed??
}
谁能给我提示我的错误在哪里?
看看我的诺言发展经验法则 。 适用于您的代码的两个特定点是:
在使用异步回调函数之前,应使其适当,特别是
var makeCall = Promise.promisify(makeAsyncCall);
总是从执行异步功能的函数中return
promise。 对于回调function() { Promise.each(…).then(…) }
来说尤其如此,例如function() { Promise.each(…).then(…) }
和function() { makeAsyncCall(…) }
。
有了这些,您应该了解以下内容:
somePromise().then(function(result) {
return Promise.each(result.cars, function(car) {
return makeCall(car.id).then(function(resultArray) {
// a lookup structure of contracts by id could make this more efficient
result.contracts.forEach(function (contract) {
if (resultArray.indexOf(contract.id) > -1)
contract.car = car.id;
});
});
}).return(result);
}).…
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.