Reputation: 95
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?
Upvotes: 0
Views: 67
Reputation: 486
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
Upvotes: 0
Reputation: 10227
return
your Promise.all(promises)
so that its result is chained to the then
where you have console.log(result)
.Promise.all(promises).then(result)
, you pass result
to then
but then
expects a function as an argument, not an objectConsider using async/await
cause it's less confusing than these Promise
chains
Upvotes: 1