简体   繁体   English

角度&异步/等待

[英]Angular & async / await

I am using the following in my angular app: 我在我的角度应用程序中使用以下内容:

let getName = greenlet( async username => {                     
    let url = `https://api.github.com/users/${username}`        
    let res = await fetch(url)                                  
    let profile = await res.json()                              
    return profile.name                                          
})                                                              

console.log(await getName('developit'));     

Angular seems to be changing this 'await' into 'yield': Angular似乎正在将这种“等待”变为“收益”:

在此处输入图片说明

How do i use this within my Angular5 application? 如何在Angular5应用程序中使用它? Thanks. 谢谢。

Babel changes async/await in the browser into generator functions, which utilize the yield keyword. Babel将浏览器中的async / await更改为生成器函数,该函数使用yield关键字。 Yields only work when they are in the correct context; 收益只有在正确的背景下才能发挥作用; specifically the next stage will be ensuring that the yield appears inside a generator function (you can read more about generators, but basically they are identified by a * in the function signature, eg function *doSomething() . 具体来说,下一阶段将确保yield出现在生成器函数中(您可以阅读有关生成器的更多信息,但是基本上它们由函数签名中的*标识,例如, function *doSomething()

A generator function will not get created if you have not correctly managed your async keywords. 如果您没有正确管理async关键字,则不会创建生成器函数。 Babel will convert that await into a generator, but because the outer function is not async, it won't create the generator wrapper, thus the error. Babel会将等待的时间转换为生成器,但是由于外部函数不是异步的,因此不会创建生成器包装,因此会出错。 Some IDEs will report this error before you compile, but that's what the error you are seeing means. 某些IDE会在编译前报告此错误,但这就是您所看到的错误的含义。

You mentioned that this console.log is sitting inside the ngOnInit lifecycle hook; 您提到此console.log位于ngOnInit生命周期挂钩中; that function call is not by itself asynchronous. 该函数调用本身不是异步的。 You can decorate it with async, but I wouldn't recommend that (it works, but what does it actually mean?). 您可以使用异步来装饰它,但我不建议这样做(它可以工作,但实际上是什么意思?)。 Instead you can try calling an explicitly async function and just ignore the returned promise: 相反,您可以尝试调用显式async函数,而忽略返回的Promise:

ngOnInit() {
    this.someFunction();
}

async someFunction() {
    console.log(await getName('developit'));
}

We'll assume for now that greenlet knows what to do with the async function it has been handed (does it resolve the promise?) 我们现在假设, greenlet知道如何处理已处理的异步函数(它可以解决诺言吗?)

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

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