繁体   English   中英

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数据,并通过映射它们将它们发送到下一个Promise:

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 (位于Promise.all )将发送请求。 在第一个.thenresponses将是responses的数组。 由于您需要响应中的实际数据,因此可以map responses以获取所需的数据。 由于此返回,它将被传递到下一个.then 此时, data将是一个数组,其中包含您要从响应中获取的数据。

然后由您决定要对此数据做什么。 如果您想将它们“组合”为一个对象,那么有很多解决方法(我可能会使用数组化简函数,但这取决于数据的结构以及您想要从中获得什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM