Saturday, 30 June 2018

Returning the result of a promise loop up one function.

I'm new to promises and working on my first project using them. I have following code ; firstpromise.then(function(result) { //console.log(result); return secondPromise(result); }).catch(function(result){ //console.log(result) }).then(function(result) { //console.log(result); return exportname.iteratePromises(result); }).catch(function(result){ //console.log(result) }); exports.iteratePromises= function (object) { new Promise(function (resolve, reject) { for (var i = 0; i < object.array.length; i++) { doNewPromise(object.array[i], object) if (i + 1 == object.array.length) { resolve(object); } } } function doNewPromise(args, object) { // is a method in the thirdPromise export file new Promise(function (resolve, reject) { request(headerOptions(args), function (error, response, body) { if (!error && response.statusCode == 200) { var result = JSON.parse(body); doStuff(); } console.log(object); resolve(object); }); }); }; So at the stage of iteratePromises I'm calling the for-loop which in itself does a request to an API for each element in the array. That request does something with the object successfully.If I console.log the doNewPromise before resolving it, it returns all data that is expected for each iteration within the array and the object is manipulated successfully.The problem I'm facing now is that I don't know how to pass that object (the one in the for-loop) back to the promise chain once all iterations have been finished.In short, how should I store/declare the returned promises from the iteratePromises execution back to the promise chain?I have tried to end the loop by usingif(i == arr.length){ end and resolve } but that keeps on returning undefined objects.I'm really at a loss as to how to approach this and any help is very much appreciated .Thank you in advance,Hexerin0

Submitted July 01, 2018 at 12:14AM by hexerin0

No comments:

Post a Comment