Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript node.js等待尚未生效的承诺_Javascript_Node.js_Promise - Fatal编程技术网

Javascript node.js等待尚未生效的承诺

Javascript node.js等待尚未生效的承诺,javascript,node.js,promise,Javascript,Node.js,Promise,在我的“app.js”中,我有一个异步函数,等待从我导入的connection.js中连接就绪 // On connection to QLab qlabconn.on('ready', () => { console.log('Connected to QLab!'); let connectionReady = new Promise(resolve => { resolve(true) }); (async () => {

在我的“app.js”中,我有一个异步函数,等待从我导入的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})
    })();
});
我不知道如何让app.js在“等待”状态下正常运行。在connection.js中,我无法在“on”函数中添加导出,也无法在on函数之外添加导出

我仍在学习承诺/等待等,因此如果能为我指出正确的方向,我将不胜感激

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})
    })();
});

如果需要基于回调的结果获得承诺,那么应该将逻辑封装在新的承诺回调中。例如,在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');
})();

在你的app.js中,
qlabconn.connectionReady
不是没有定义吗?承诺的全部意义在于你可以承诺一些还不可用的东西。另请参阅