0

I have a function which is returning a promise (parent function). Inside that function I need to wait for another function (child function) which is also returning a promise. This happends after about 500ms. But inside the parent function I also have an event listener, for which is emitted after 1-3 minutes, after the child function has returned. The data of this event is very important, and also needs to be passed back to the parent function somehow. What I want is to call the parent function, and still get the event listener data, but I dont want to wait 1-3 minutes for each parent function to be called.

I managed to throw back the event listener data through a callback function, and this works - but I dont know if this is the right way to do it.

Here is my sample code.

function parent(data: Buffer, callback: (acknowledged: boolean) => void): Promise<any> {
    return new Promise(async (resolve, reject) => {
        e.on("data", function _listener(data) {
            if (data[0] === CMD_ACK ) {
                e.removeListener("data", _listener);
                return callback(true);
            }
            else if (data[0] === CMD_NON_ACK) {
                e.removeListener("data", _listener);
                return callback(false);
            }
        });
        try {
            let frame: Buffer = Buffer.from([0x01, 0x02, 0x03]);
            await child(frame); // this takes < 500ms
            resolve(); // I must resolve here, and not in callback, else it takes 2-3 minutes, before I can call parent function again.
        } catch (error) {
            reject(error);
        }
    })
}
Simon
  • 83
  • 8
  • [Never pass an `async function` as the executor to `new Promise`](https://stackoverflow.com/q/43036229/1048572)! – Bergi Nov 03 '20 at 08:09
  • Yes, using a callback is fine. However, the standard approach would be to have the first promise resolve with an object that contains both the frame and the second promise (assuming that `data` *always* fires only after `child` fulfills) – Bergi Nov 03 '20 at 08:27
  • (See https://stackoverflow.com/q/32168194/1048572) – Bergi Nov 03 '20 at 08:54

0 Answers0