简体   繁体   English

为promise结果对象的每个数组元素调用异步函数,进行更改并返回此对象

[英]call async function for each array element of a promise result object, make changes and return this object

A Bluebird Promise returns an object that contains two arrays of objects, cars and contracts. 蓝鸟承诺会返回一个对象,其中包含对象,汽车和合同的两个数组。 Then, I want to iterate over the cars, call an asynchronous function and, based on the returned value, make some changes to the second array and return the initial result object with these changes. 然后,我要遍历汽车,调用异步函数,然后根据返回的值对第二个数组进行一些更改,并使用这些更改返回初始结果对象。 I can't figure out how to do this with promises. 我不知道如何用诺言做到这一点。 Or with async, for that matter. 或与异步,为此。 I feel like they should be nested promises, but i can;t get it to work at all. 我觉得它们应该是嵌套的承诺,但是我根本无法使它工作。

the version with promises: 承诺版本:

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??
}

Can anyone give me a hint as to where my mistake is? 谁能给我提示我的错误在哪里?

Have a look at my rules of thumb for promise development. 看看我诺言发展经验法则 The two specific points that apply to your code are: 适用于您的代码的两个特定点是:

  • promisify your async callback-taking functions before using them, specifically 在使用异步回调函数之前,应使其适当,特别是

     var makeCall = Promise.promisify(makeAsyncCall); 
  • always return promises from your functions that do asynchronous things. 总是从执行异步功能的函数中return promise。 This is especially true for callbacks, like the function() { Promise.each(…).then(…) } and the function() { makeAsyncCall(…) } . 对于回调function() { Promise.each(…).then(…) }来说尤其如此,例如function() { Promise.each(…).then(…) }function() { makeAsyncCall(…) }

With those, you should get to the following: 有了这些,您应该了解以下内容:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM