The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.
They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events. In other words also, we may say that, promises are the ideal choice for handling multiple callbacks at the same time, thus avoiding the undesired callback hell situation.
When using Javascript promises, does the event loop get blocked? No. Promises are only an event notification system.
Don't do any await
ing inside the Promise
constructor - you only should do the promisification of the asynchronous callback in there:
async function fn() {
await a();
await b();
await c(); // this causes myEvent
return new Promise(function(resolve, reject) {
thing.once('myEvent', function(e) {
resolve(e.data); // done
});
});
}
The thing that starts the process which eventually causes the event to be emitted is usually called inside the Promise
executor callback as well (to catch synchronous exceptions), but usually it doesn't return a promise like your c
function does.
Maybe this expresses the intent better:
async function fn() {
await a();
await b();
const {data} = await new Promise(resolve => {
thing.once('myEvent', resolve);
thing.c(); // this causes myEvent
});
return data;
}
Of course this assumes that you only need to start listening to the event when you've called the other ones. If you expect the event to fire before that, you essentially have a race with parallel execution - I'd recommend to use Promise.all
in that case:
async function fn() {
await a();
await b();
const [{data}, cResult] = await Promise.all([
new Promise(resolve => thing.once('myEvent', resolve)),
c()
]);
return data;
}
If you have node v11.13.0 or higher you can use the events.once
method so that you don't have to build the promise yourself - and it also handles error events correctly:
import { once } from 'events';
async function fn () {
await a()
await b()
await c()
await once(thing, 'myEvent')
}
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