异步功能和Readline使用

时间:2019-03-09 13:26:42

标签: javascript node.js asynchronous

我想同时使用异步功能和readline。在readline上写输入后,我想转到第二个主题(.then)。但这不等我写完文字。我想在控制台上看到phoneCode,但得到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);
  });

2 个答案:

答案 0 :(得分:1)

readline.question立即返回。收到用户输入时,它将调用回调。因此,return phoneCode是在更新phoneCode之前执行的。您可以从第二个.then块返回一个Promise,并在调用readline回调时调用其resolve

//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);

答案 1 :(得分:1)

首先,我们将readline.question()方法从基于回调的API转换为基于承诺的API:

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

现在,您可以在示例中继续.then()来返回它:

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

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

这与

相同
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);
  });