4

Hi I have async nodejs function where I am using stream concept. I want once stream is completed then I want to return from this function.

const removeMapping = async function (query) {

    let stream = query.foreach();
    stream.on('data', function (record) {
       client.delete(record);
    })
    stream.on('error', function (error) {

    })
    stream.on('end', function () {
        console.log("completed");
    })
};

I am calling this function like this but after execution of this line, stream async code after this.

await mapping.deleteMapping(cookie);

Does anyone know how to handle this ?

N Sharma
  • 33,489
  • 95
  • 256
  • 444

1 Answers1

11

Your function doesn't need to be async as you are not calling await within the function.

What you can do is return a new promise:

const removeMapping = function (query) {

    return new Promise((resolve, reject) => {

        let stream = query.foreach();
        stream.on('data', function (record) {
            client.delete(record);
        })
        stream.on('error', function (error) {
            reject(error);
        })
        stream.on('end', function () {
           resolve("completed");
        })

    })

};

You can then resolve or reject depending on what comes back from your stream.

Stretch0
  • 8,362
  • 13
  • 71
  • 133
  • You are resolving multiple times because I assume on data will be executed more than one, how do you handle that? – Nicolas Del Valle Oct 31 '19 at 19:21
  • Then don't put a resolve in your on data listener. Just have the resolve in on end. What do you want to do when you receive data? (Updated answer to reflect this) – Stretch0 Oct 31 '19 at 19:28