简体   繁体   English

在角度6中使用toPromise的正确方法

[英]The right way to use toPromise in angular 6

I'm trying to retrieve data from multiple http requests and i decided to avoid nested subscribe(). 我正在尝试从多个http请求中检索数据,我决定避免使用嵌套的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 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. 正如您所注意到的, .toPromise方法的结果是Promise对象。 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. 为了使用async / await样式,首先需要使用异步函数包装代码,方法是在函数前加上async关键字,然后使用await关键字告诉代码等待异步操作。 In your case it's http request. 在你的情况下它是http请求。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM