[SOLVED] export values from async function


This Content is from Stack Overflow. Question asked by Pratheek Reddy

in test.js, I have some callback that resolves “a” value. then further the “a” value is exported at the end of the file

let fun = async ()=>{
let a
    await setTimeout(()=>{a = 10}, 100)
    return a

let a  
export default a

when im trying to import a value in test1.js, im getting a as undefiner

import a from './test.js'

console.log(a) //undefined


let is lexically scoped to the nearest block, so you actually have two different variables named a that just happen to have the same name.

The solution would be to use top-level await to export a Promise, for example:

export default await Promise.resolve(10)

This Question was asked in StackOverflow by Pratheek Reddy and Answered by Nick McCurdy It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?