[英]How to call an async arrow function with await
If I define a function like this: 如果我定义这样的函数:
const getName = async () => await Promise.resolve('John');
When I try to call the getName function with async: 当我尝试使用async调用getName函数时:
const name = await getName();
console.log(`Hi ${name}`);
It throws an error: 它抛出一个错误:
const name = await getName();
^^^^^
SyntaxError: await is only valid in async function
What I'm doing wrong? 我做错了什么?
const getName = async () => await Promise.resolve('John');
In the above, you have an async function (the arrow function) which uses await
inside. 在上面,你有一个使用
await
inside的异步函数(箭头函数)。
This is fine (albeit pointless as you could return the promise directly). 这很好(虽然没有意义,因为你可以直接返回承诺)。
Here: 这里:
const name = await getName();
You use await
again, and while the function on the right-hand side does return a promise, the function it appears inside is not async
so it is not valid. 你再次使用
await
,虽然右侧的函数确实返回了一个promise,但它里面出现的函数并不是async
所以它是无效的。
Put it inside an async function and it will be fine: 把它放在一个异步函数里面就可以了:
const getName = async() => await Promise.resolve('John'); const init = async() => { const name = await getName(); console.log(`Hi ${name}`); }; init();
As mentioned though, making getName
async
and await
ing inside is just a needlessly complex set of nested promises and you could simplify: 如上所述,使
getName
async
并await
内部只是一组不必要的复杂的嵌套promise,你可以简化:
const getName = () => Promise.resolve('John'); const init = async() => { const name = await getName(); console.log(`Hi ${name}`); }; init();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.