【问题标题】:node.js await on not yet avaliable promise [duplicate]node.js等待尚未可用的承诺[重复]
【发布时间】:2020-01-17 12:43:33
【问题描述】:

在我的“app.js”中,我有一个异步函数等待从我导入的 connection.js 中准备好连接

我不确定如何让 app.js 在“等待”的情况下正常运行。在 connection.js 中,我无法在“on”函数中添加导出,也无法在 on 函数之外添加。

我仍在学习 promises/await 等,因此我们将不胜感激。

app.js

var qlabconn = require('./qlab/connection.js');

// Wait for QLab connection, then we'll start the magic!
(async () => {
    console.log('Ready!');
    var qlabConnectionReady = await qlabconn.connectionReady;
    //qlab.cues.x32_mute('1', "OFF");
    console.log(qlabConnectionReady);
})();

connection.js

// On connection to QLab
qlabconn.on('ready', () => {
    console.log('Connected to QLab!');
    let connectionReady = new Promise(resolve => {
        resolve(true)
    });

    (async () => {
        await core.send_message(`/alwaysReply`, {"type" : 'f', "value" : 1})
    })();
});

【问题讨论】:

标签: javascript node.js promise


【解决方案1】:

如果您需要根据回调的结果获取 Promise,则应将逻辑包装在新的 Promise 回调中。比如在connection.js中:

// return a reference to qlabconn once we have established a connection
module.exports = function getConnection() {
  return new Promise((resolve, reject) => {
    // let qlabconn = new QLabConnection(...)
    qlabconn.on('ready', () => resolve(qlabconn));
  })
}

然后,我们就可以在 app.js 中正常使用连接对象了。

const getConnection = require('./connection');

(async () => {
  let qlabconn = await getConnection();
  console.log(qlabconn.connectionReady);

  await core.send_message(`/alwaysReply`, {type: 'f', value: 1});
  console.log('Connected to QLab!');
  // qlab.cues.x32_mute('1', 'OFF');
})();

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2018-01-05
    • 2018-04-17
    • 2015-08-15
    • 2022-01-22
    相关资源
    最近更新 更多