javascript - 在 ES6/Typescript 中链接 promises

标签 javascript typescript ecmascript-6 es6-promise fetch-api

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

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())
])

关于javascript - 在 ES6/Typescript 中链接 promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39736981/

相关文章:

javascript - Polymer 2.0 边缘问题

javascript - 选择的自定义绑定(bind)无法将对象作为值处理

typescript - 如何在定义为 "any"的第三方 TypeScript 接口(interface)中增加属性?

javascript - 在JS中正确使用typeof运算符?

javascript - 意外的 token ,但不确定原因

javascript - 解析具有重复键的嵌套 JSON 对象(PHP 或 JS)

javascript - 使用 JS/DOM 创建带有 <param> 的 <object>

Angular2/PrimeNG - 无法显示下拉列表

visual-studio - VS2015 : Adding "watch": true to tsconfig. json 导致 JsErrorScriptException (0x30001)

node.js - 为什么 VSCode 调试器总是将 Node 导入显示为未定义?