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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With