在 ES6/Typescript 中链接承诺

Chaining promises in ES6/Typescript

我需要链接承诺以发出多个 GET 请求并合并数据,然后再将其用于其他地方。我很难解决这两个承诺。在尝试使用 .json() 之前,我尝试返回两个承诺的数组,但这也不起作用。

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

console.log(响应)的输出; :

[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

谢谢!

您似乎在寻找

return Promise.all([responses[0].json(), responses[1].json()]);

或者直接做

this.photos = Promise.all([
    this.http.fetch('photos').then(response => response.json()),
    this.http.fetch('photos2').then(response => response.json())
])

您可以从响应中提取您想要的 json 数据,并通过映射将它们发送到下一个承诺:

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

第一个承诺(在 Promise.all 中)将发送请求。在第一个 .then 中,responses 将是一个响应数组。由于您需要响应中的实际数据,因此可以 map over responses 来获取所需的数据。既然这个returns那个,就会传到下一个.then。此时,data 将是一个数组,其中包含您希望从响应中获得的数据。

然后由您决定要如何处理这些数据。如果你想 "combine" 它们成为一个单一的对象,那么有很多方法可以实现(我可能会使用数组 reduce 函数,但这取决于数据的结构和你想要的东西它。