【发布时间】:2017-02-05 19:30:11
【问题描述】:
我需要链接 promise 以发出多个 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(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
谢谢!
【问题讨论】:
-
console.log(responses[0].json(), responses[1].json())。有什么承诺吗?我怀疑json()是异步的。 -
@Ryan 不必如此。它可以是传递给下一个承诺的值。
-
是的,它记录了两个用正确数据解析的 Promise。我不能正确地将事物作为我的数据变量传递。如果我通过
responses(注释掉)然后尝试在下一个承诺中以相同的方式(.json)访问它们,我会得到两个未定义值的未决承诺。 -
return Promise.all(responses.map(r => r.json()));,然后呢? -
@bmb242 删除了我的答案... Ryan 的建议正是您所需要的。获得结果对象后,将它们合并到适合您的用例并为下一个 Promise 处理程序返回合并的对象。
标签: javascript typescript ecmascript-6 es6-promise fetch-api