我需要链接 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/