Search code examples
javascriptcallbacksocket.iopromisees6-promise

How do I convert this callback argument into a promise?


I am using socket.io and I'd like to convert the callback function into a simple promise based function where I can return a value.

I'm trying to convert the acknowledgement found here: socket.io/docs/#sending-and-getting-data-(acknowledgements)

socket.on('getGames', (data, callback) => {
    Game.find(data)
        .then(data => callback(data)); //explicit call to callback
});

I'd like to call a function instead such as:

socketEvent(socket, 'getGames')
    .then((data) => {
        return Game.find(data); //returns a promise and can be chained
    });

I'm thinking something like:

//this doesn't work
const socketEvent = (socket, name) => {
    return new Promise(function (resolve, reject) {
        socket.on(name, (data, callback) => {
            resolve((data) => callback(data));
        });
    });
};

Solution

  • Your second code snippet is not analogous to the first. In the first one, there is a mechanism to send an acknowledgement when Game.find() has retrieved its value, but in the second one, there's no way for it to send the acknowledgement back when its done.

    I think this might be close to what you are trying to do:

    const socketEvent = (socket, name) => {
        return new Promise(function (resolve, reject) {
            socket.on(name, (data, sendBack) => resolve({ data, sendBack }));
        });
    };
    

    You could then consume it like this:

    socketEvent(socket, 'getGames')
        .then({ data, sendBack } => Game.find(data).then(sendBack))
        .then(... more stuff);
    

    However, as others have pointed out, there is still a LARGE difference between this and the original code because the promise version will only capture the event once (that's how promises work). If you need to set up a mechanism to capture the same event multiple times, then promises are not the right tool for the job and you either need to use callbacks, or something like observables.