简体   繁体   English

await (async ():Type => {return value})():: error 找不到名称'await'.ts(2304)

[英]await (async ():Type => {return value})() :: error Cannot find name 'await'.ts(2304)

// Does not work - Cannot find name 'await'.ts(2304)
let someVariable = await (async ():someType => {
   // i need to use await inside here so i need it async
   return someValue;
})();

// does work, but not async.
let someVariable2 = (():someType => {
   // cant use await inside
   return someValue
})();

i tried wrapping await inside another set of curved brackets, still doesnt work.我尝试将 await 包裹在另一组弧形括号内,仍然无法正常工作。 yes i know i can declare a function then call it like you would normally, but i'd rather have it like this.是的,我知道我可以声明一个 function 然后像往常一样调用它,但我宁愿这样。 if it isnt possible then ill go back to the normal way.如果不可能,则将 go 恢复正常。

i do not know fully what () does in cases like this, but im assuming it returns the object inside.我不完全知道()在这种情况下会做什么,但我假设它会返回 object 内部。 is it possible to use async/await like this?可以像这样使用 async/await 吗? if possible would also like to learn more about how () works in cases like this.如果可能的话,还想了解更多关于()在这种情况下如何工作的信息。

code runs on Deno代码在 Deno 上运行
edit: people saying "await must be used inside an async block" Deno has top-level await.编辑:人们说“必须在异步块内使用等待” Deno 具有顶级等待。

Clarifying.澄清。

// this is top-level
async function somefunc() {}
await somefunc(); // this WORKS on deno.

issue is let var = await(async () => {})() creates said error, and i am trying to find a way to fix this with a other way than declaring then await it问题是let var = await(async () => {})()创建了上述错误,我试图找到一种方法来解决这个问题,而不是声明然后等待它

edit: https://github.com/microsoft/TypeScript/issues/38483编辑: https://github.com/microsoft/TypeScript/issues/38483

Await has to be called inside a async function. Await 必须在异步 function 中调用。

 const aFunc = async () =>{ let someVariable = await (async ():someType => { const someValue = await asyncFunc() return someValue; })(); // Now you get the value console.log(someVariable) } aFunc()

Now You can call aFunc function to make it work现在您可以调用aFunc function 使其工作

await can only within an async block. await只能在异步块内。 Make sure outside await is also within an async block or you can save the promise within someVariable .确保外部 await 也在异步块中,或者您可以将 promise 保存在someVariable中。


let someVariable = (async ():someType => {
   return someValue;
})();

someVariable.then((result) => {
 // result contains whatever u returned in the async block.
})

 const someVariable = (async () => { const result = await Promise.resolve('Hey there;') return result. })() someVariable.then(result => console.log({ result }))

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

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