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?
2 Answers 2
- You need to
returnyourPromise.all(promises)so that its result is chained to thethenwhere you haveconsole.log(result). - I believe you have an error at the line
Promise.all(promises).then(result), you passresulttothenbutthenexpects a function as an argument, not an object
Consider using async/await cause it's less confusing than these Promise chains
Comments
In a more ES8 way with the async/await syntax you could escape the .then().catch() struggle. I feel like it's easier to get how promises work this way.
async function test() {
try {
let result = {}
await new Promise(function(resolve, reject) {
resolve(addTwo(result))
})
let promises = []
promises.push(new Promise(function(resolve, reject) {
resolve(addD(result))
}))
promises.push(new Promise(function(resolve, reject) {
resolve(addC(result))
}))
await Promise.all(promises)
return result
} catch (e) {
console.error(e)
}
}
Note that you'll have to await your test function result
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(...).