bmb242 bmb242 - 2 months ago 13
TypeScript Question

Chaining promises in ES6/Typescript

I need to chain promises to make several GET requests and combine the data before using it elsewhere. I am having difficulty resolving the two promises. I've tried returning an array of the two promises before trying to use

.json()
but that doesn't work either.

activate() {

// data is from http://jsonplaceholder.typicode.com/photos and
// since there is not a photos2/ endpoint this is conceptual and
// represents batch importng
return Promise.all([
this.http.fetch('photos'),
this.http.fetch('photos2')
]).then(responses => {

console.log(responses); // see block of code below this for output

// how can I combine the two promises here so I can resolve them with 'then' below?
return responses[0].json(); // can return one response
// return responses; // doesn't work

}).then(data => {
console.log(data);
this.photos = data;

}).catch(err => {
console.log(err);
});
}


output of console.log(responses); :

[Response, Response]
0: Response
body: (...) // readablebytestream
bodyUsed : false
headers : Headers
ok : true
status : 200
statusText : "OK"
type : "cors"
url : "http://jsonplaceholder.typicode.com/photos"
__proto__ : Object
1 : Response
....etc


Thank you!

Answer

You can extract the json data you want from the responses and send them to the next promise by mapping over them:

activate() {
    return Promise.all([
        this.http.fetch('photos'),
        this.http.fetch('photos2')
    ]).then(responses => {

        // this will send the actual json data 
        // you want to the next chained promise
        return responses.map(response => response.json())

    }).then(data => {

        // data is now an array of the the json objects 
        // you are trying to get from the requests
        console.log(data);
        this.photos = data;

    }).catch(err => {
        console.log(err);
    });
}

The first promise (in Promise.all) will send the requests. In the first .then, responses will be an array of the responses. Since you want the actual data from the responses, you can map over responses to get the data you want. Since this returns that, it will be passed into the next .then. At this point, data will be an array with the data you want from the responses.

It is then up to you to decide what you want to do with this data. If you want to "combine" them into a single object, then there are many ways to go about it (I would probably use the array reduce function for it, but that depends on the structure of the data and what you want from it.

Comments