javascript 在 angular 6 中使用 toPromise 的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51341087/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The right way to use toPromise in angular 6
提问by sandum
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.
我正在尝试从多个 http 请求中检索数据,我决定避免嵌套 subscribe()。我只想以异步等待风格编写代码。
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()
采纳答案by Jake Kalstad
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 => {})
myPromiseArray.push(this.http.get(url, {params: params}).toPromise())
Promise.all(myPromiseArray).then(alltheValuesInAnArray => {})
回答by Nurik Nurmetov
As you noticed, the result of .toPromisemethod is Promise object. In order to use async/await style, you need at first wrap your code with async function, by prepending asynckeyword to function, and then with awaitkeyword tell your code to wait for async operation. In your case it's http request.
如您所见,.toPromise方法的结果是 Promise 对象。为了使用 async/await 风格,你首先需要用 async 函数包装你的代码,通过async在函数前面加上关键字,然后用await关键字告诉你的代码等待异步操作。在您的情况下,它是 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();

