abbott567 abbott567 - 1 month ago 15
Node.js Question

Sequential Promises whilst passing values

I am playing around with the destiny API, and I have run into a bit of an issue. If I request a characters details, it returns an object, but the values are ID's, which then need to be passed into another API call to 'the manifest' which returns an object for that ID.

I am making the API calls using 'request-promise' but it means I am having to nest calls which I don't feel happy about.

I need to keep some of the data from the first request, and then make another call to get the final piece of data.

eg:


request('destiny-character-api')
.then(character => {
// Keep some of the data from character, eg className
request(`destiny-manifest-api/${character.item}`)
.then(item => {
// Overwrite character.item with the value of item.name
return item;
});
});


I need a way to hold off the second request until the first one has returned, and then pass the returned value into the second request.

Thanks

Answer

Instead of nesting calls, you could chain your promises, like so:

request('destiny-character-api')
.then(character => {
    return request(`destiny-manifest-api/${character.item}`);
})
.then(item => {
    return item;
});

If you need to pass some data on from the first success handler to the second, then return a Promise.all(), passing in an array with your second request, along with any data that you want to send along. e.g.,

request('destiny-character-api')
.then(character => {
    return Promise.all([
        request(`destiny-manifest-api/${character.item}`),
        character.className
    ]);
})
.then(([item, className]) => {
    item.name = className;
});
Comments