Reputation: 942
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':
How do i use this within my Angular5 application? Thanks.
Upvotes: 1
Views: 1252
Reputation: 171
Babel changes async/await in the browser into generator functions, which utilize the yield
keyword. 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, e.g. function *doSomething()
.
A generator function will not get created if you have not correctly managed your async
keywords. 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. Some IDEs will report this error before you compile, but that's what the error you are seeing means.
You mentioned that this console.log is sitting inside the ngOnInit
lifecycle hook; 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:
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?)
Upvotes: 2