Sequential Promises whilst passing values

时间:2016-10-20 12:44:16

标签: javascript node.js request promise es6-promise

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

2 个答案:

答案 0 :(得分:1)

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;
});

答案 1 :(得分:0)

If you don't want to nest calls you can return the request promise and continue in flat style.

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

This way the code will be flat. Read about promise chaining.

Don't know what you mean by holding off the second request.... in this code, the second request will fire after the first has completed.