简体   繁体   中英

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. yes i know i can declare a function then call it like you would normally, but i'd rather have it like this. if it isnt possible then ill go back to the normal way.

i do not know fully what () does in cases like this, but im assuming it returns the object inside. is it possible to use async/await like this? if possible would also like to learn more about how () works in cases like this.

code runs on Deno
edit: people saying "await must be used inside an async block" Deno has top-level await.

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

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

Await has to be called inside a async 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

await can only within an async block. Make sure outside await is also within an async block or you can save the promise within 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 }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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