Reputation: 11
I use the request-promise
node module as following :
let rp = require('request-promise');
I have the following promises chain :
getData().then( data => {
return getUser(data);
})
.then( data => {
return getProfiles(data);
}).then( data => {
updateAddresses(data);
});
The updateAddresses
is as following :
function updateAddresses(data){
var promises = data.map( (aProfile) => {
var options = {url:'http://example.com', method:'POST'};
return rp(options);
});
// Promise.all(promises).then(...);
}
So I'm preparing a promise (request-promise) for each element of the array.
The problem is that those promises are firing even when I remove Promise.all
!
How is that possible ? How can I make the promise not firing ?
Regards.
Upvotes: 1
Views: 1401
Reputation: 169
You could do what zero298 suggested in his edit.
the main problem is that you map your data to an actual promise, rather than something that is ready to execute a promise,
compare
Let promises = Options.map(option => execute(option))
Promise.all(promises)
With
Let promiseGenerators =Options.map(option => () => execute(option))
Promise.all(promiseGenerators.map(generator => generator())
The second you call the function that will return the promise, it will start doing it. That's where the problem was, because you called rp(options) too soon.
Upvotes: 1
Reputation: 26919
Your updateAddresses
is not returning anything to call then()
on and you aren't waiting on what would be coming out of updateAddress
.
function updateAddresses(data){
var promises = data.map( (aProfile) => {
var options = {url:'http://example.com', method:'POST'};
return rp(options);
});
//Return something to then()
return Promise.all(promises).then(...);
}
Then wait on it:
getData().then( data => {
return getUser(data);
})
.then( data => {
return getProfiles(data);
}).then( data => {
return updateAddresses(data);
}).then(e => somethingelse);
Per your requirement to store the map
ped address Objects:
function updateAddresses(data) {
return data.map((aProfile) => {
return {
url: 'http://example.com',
method: 'POST'
}
});
}
getData()
.then(data => getUser(data))
.then(data => getProfiles(data))
.then((data) => {
let addressOptions = updateAddresses(data);
/*
* You now have an Array of Objects of the form:
* {
* url: "",
* method: "",
* }
*/
return Promise.resolve(addressOptions);
})
.then(addressOptions => Promise.all(addressOptions.map(address => rp(address))))
.then((arrayOfResolvedData) => {
/*
* arrayOfResolvedData is an Array of data per whatever rp() returns
* probably Response Objects
*/
console.log(arrayOfResolvedData);
})
Upvotes: 1