Home > Enterprise >  export values from async function
export values from async function

Time:09-19

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

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

let a  
fun().then(val=>{a=val})
export default a

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

test1.js
import a from './test.js'

console.log(a) //undefined

CodePudding user response:

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)

CodePudding user response:

This should work

test.js

// this does what you attempted to do
// but actually works
let fun = async () => {
    let a = await new Promise(r => setTimeout(r, 100, 10));
    return a;
};

let a = await fun();
export default a;

test1.js

import a from './test.js'
console.log(a)
  • Related