[英]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
)將發送請求。 在第一個.then
, responses
將是responses
的數組。 由於您需要響應中的實際數據,因此可以map
responses
以獲取所需的數據。 由於此返回,它將被傳遞到下一個.then
。 此時, data
將是一個數組,其中包含您要從響應中獲取的數據。
然后由您決定要對此數據做什么。 如果您想將它們“組合”為一個對象,那么有很多解決方法(我可能會使用數組化簡函數,但這取決於數據的結構以及您想要從中獲得什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.