I am new to node.js and I am having hard time with Promises. I want to construct/build my result variable step by step by using Promises.
I "abstracted" my code just to point out the issue better. Basically what I am trying to do is to create a resulting model of several rest api calls (those calls that can be done in parallel are called in Promise.all).
Thank you in advance.
function test() {
var result = {};
var prom1 = new Promise(function(resolve, reject) {
resolve(addTwo(result));
}).catch(err => console.log(err));
return prom1.then(function(result) {
promises = [];
promises.push(new Promise(function(resolve, reject) {
resolve(addD(result));
}));
promises.push(new Promise(function(resolve, reject) {
resolve(addC(result));
}));
Promise.all(promises)
.then(result)
}).then(console.log(result)); //logging because I was testing
}
function addTwo(result) {
result.a = "a";
result.b = "b";
return result;
}
function addD(result) {
result.d = "d";
}
function addC(result) {
result.c = "c";
}
test();
The output that expected was: { a: 'a', b: 'b', d: 'd', c: 'c' }, but instead I got: { a: 'a', b: 'b' }
I understand that if I call then() on a Promise, that I will have in that block access to the return value from the promise, but can I adjust my code somehow to "build" the result variable in the then calls with using Promise.all at some point?
then, like.then(() => { return result })or.then(() => { console.log(result); }).addTwo,addCandaddDcreate andreturnthe promises themselves. Also you don't neednew Promisehere, you could just have usedPromise.resolve(…).