Reputation: 6693
How should a Promise async function be done combining with event?
function f() {
return promisedFunction().then(event => {
let buf = '';
event.on('data', data => {
buf += data.toString()
});
event.on('end', () => {
return buf;
});
// how should I return buf here so that the promise would resolve fine?
});
}
Upvotes: 1
Views: 286
Reputation: 1074355
This is one of those few situations where you can't avoid creating a new promise. You'd do that in then
and return it:
function f() {
return promisedFunction().then(event => {
return new Promise((resolve, reject) => {
let buf = '';
event.on('data', data => {
buf += data.toString()
});
event.on('end', () => {
resolve(buf);
});
event.on(/*...presumably there's an error condition?...*/, () => {
reject(/*..details of error..*/);
});
});
});
}
Easily 90% of the time, you already have a promise to work with (and one of the most common errors with promise is creating them when you don't have to), but you don't have one you can use to wait for the events in your example.
Upvotes: 5