Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until stream async is executed in nodejs [duplicate]

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 ?

like image 564
N Sharma Avatar asked Sep 11 '25 00:09

N Sharma


1 Answers

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.

like image 166
Stretch0 Avatar answered Sep 12 '25 13:09

Stretch0