2

I want to use async function and readline same time. After I write to input on readline, I want to go to the second thried (.then). But it doesn't wait to I write to the text. I want to see phoneCode on console but I get beforeCode.

let phoneCode = "beforeCode";
const asenkronFonksiyon = () => {
  return new Promise((resolve, reject) => {
    resolve();
  });
};

asenkronFonksiyon()
  .then(data => {
    return data;
  })
  .then(data => {
    readline.question(`What's code?`, code => {
      console.log(`Hi ${data}!`);
      phoneCode = code;
      readline.close();
    });
    return phoneCode;
  })
  .then(data => {
    console.log("phoneCode" + phoneCode);
  });
Samuel Vaillant
  • 3,667
  • 1
  • 14
  • 21
Meltem
  • 89
  • 1
  • 9
  • Callbacks don't "just work" with promise chains. You have to convert the callback to a promise that resolves within the callback, and `return` that from the continuation in order to prevent from breaking out of the chain. – Patrick Roberts Mar 09 '19 at 13:33
  • do you have any example for that? Because I am new and I couldn't understand :( – Meltem Mar 09 '19 at 13:39

2 Answers2

1

readline.question returns immediately. It calls the callback when user input is received. Hence, return phoneCode is executed before the phoneCode is updated. You can return a Promise from the second .then block, and call its resolve when the readline callback is called

//Other promises
.then(data=>{
  return new Promise(resolve=>{
    readline.question(`What's code?`, code => {
      console.log(`Hi ${data}!`);
      readline.close();
      resolve(code);
    });
  });
})
.then(code=>phoneCode=code);
jro
  • 900
  • 1
  • 10
  • 21
1

First let's start by converting the readline.question() method from a callback-based API to a promise-based API:

const question = prompt => new Promise(resolve => {
  readline.question(prompt, resolve);
});

Now you can return it from the .then() continuation in your example:

const asenkronFonksiyon = async () => {
  // ...
};

asenkronFonksiyon()
  .then(data => {
    return question(`What's code?`);
  })
  .then(phoneCode => {
    readline.close();
    console.log("phoneCode" + phoneCode);
  });

This makes it the same as

const asenkronFonksiyon = async () => {
  // ...
};

asenkronFonksiyon()
  .then(data => {
    return new Promise(resolve => {
      readline.question(`What's code?`, code => {
        resolve(code);
      });
    });
  })
  .then(phoneCode => {
    readline.close();
    console.log("phoneCode" + phoneCode);
  });
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153