0

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!

2
  • await keyword waits on promise does your function readline.question returns a promise? Commented Nov 28, 2020 at 12:15
  • Readline's question() function does not return Promise or result of the arrow function. So, cannot use then() with it. @alt255 Commented Nov 28, 2020 at 12:24

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly want I needed! Thanks for the reply! @alt255

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.