arevilla009
arevilla009

Reputation: 453

How to get a variable value outside a callback function NodeJS

I'm trying to get the value of an inputed variable on a callback function and assign it into another variable value outside this callback function. I'm using async/await but not working (the assignment runs before the callback function), any suggestion?

async function iniciar() {
    let my_prep = '';
    await readline.question('Insert preposition', (prep) => {
      **my_prep = prep;**
      readline.close();
    });
    console.log('OK',my_prep);
    return true;
}

enter image description here

Thanks for reading!

Upvotes: 0

Views: 1250

Answers (1)

alt255
alt255

Reputation: 3566

You can do something like this.

const question = () => {
  return new Promise((resolve, reject) => {
    readline.question('Insert preposition ', (prep) => {
      readline.close();
      resolve(prep)
    })
  })
}



async function iniciar() {
  let my_prep = await question();
  console.log('OK',my_prep);
  return true;
}

await keyword waits on the promise to resolve, so you need to return promise. Also the use of async/await and promises is to avoid callback hell.

Upvotes: 4

Related Questions