Javascript node.js等待尚未生效的承诺
在我的“app.js”中,我有一个异步函数,等待从我导入的connection.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 () => {
// 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
不是没有定义吗?承诺的全部意义在于你可以承诺一些还不可用的东西。另请参阅