0

In my "app.js" I have an async function waiting for a connection to become ready from my imported connection.js

I'm not sure how I can get app.js to function correctly with it's "await". In connection.js, I'm not able to add an export in the 'on' function, nor outside the on function.

I'm still learning promises/await's etc so pointers in the right direction would be appreciated.

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})
    })();
});
Scott Robinson
  • 583
  • 1
  • 7
  • 23
  • isn't `qlabconn.connectionReady` undefined in your app.js? – Federkun Sep 16 '19 at 16:37
  • The whole point of promises is that you can *make a promise* for something that is not yet available. – Bergi Sep 16 '19 at 18:24
  • See also https://stackoverflow.com/questions/37426037/promises-for-promises-that-are-yet-to-be-created-without-using-the-deferred-ant/37426491#37426491 – Bergi Sep 16 '19 at 18:25

1 Answers1

1

If you need to get a promise based on the result of a callback, you should wrap the logic in a new Promise callback. For example, in 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));
  })
}

Then, we can use the connection object as normal in 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');
})();
Brian
  • 1,860
  • 1
  • 9
  • 14