I'm trying to retrieve data from multiple http requests and i decided to avoid nested subscribe(). I just want to write code in async await style.
const diagnostics = this.http.get(url, {params: params}).toPromise()
console.log(diagnostics);
But i get this:
// ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
Which i don't know how to handle to extract data.
Is there a way to avoid callbacks like ?
.then(res => {}).catch()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
Sounds like you may want to look at this, you can collate an array of promises and can essentially "await" on all of them to complete before acting on the value.
myPromiseArray.push(this.http.get(url, {params: params}).toPromise()) Promise.all(myPromiseArray).then(alltheValuesInAnArray => {})
As you noticed, the result of .toPromise
method is Promise object. In order to use async/await style, you need at first wrap your code with async function, by prepending async
keyword to function, and then with await
keyword tell your code to wait for async operation. In your case it's http request.
async function run(){
try{
const diagnostics = await (this.http.get(url, {params: params}).toPromise());
// wait for asynchronous request
console.log(diagnostics);
} catch(err){
// request failed
console.error(err);
}
}
run();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.