3 ms·
It’s the cleanest way to wrap a event-emitting library, for example. async/await is not applicable in such a case where resolve needs to be explicitly called in
by eurasiantiger 5y ago
It’s the cleanest way to wrap a event-emitting library, for example. async/await is not applicable in such a case where resolve needs to be explicitly called in a callback.
async function process() {
return new Promise((resolve, reject) => {
emitter.on(”error”, (err) => reject(err));
emitter.on(”end”, (result) => resolve(result));
emitter.start();
});
}
async is not strictly needed here, but I find it a good practice to use it on functions which immediately return a Promise anyway.
- deleted 5y ago[deleted]
- zkldi 5y agoI don't think it's a good practice, atleast if you have typescript jn your stack. It's redundant and wraps the promise in another promise.
- eurasiantiger 5y agoIIRC that doesn’t actually happen if a native Promise is returned.
- eyelidlessness 5y agoIt does, but only if you also add a redundant await. Which I still do, even in TypeScript, unless there’s a compelling performance reason not to. I disagree with the article overall, but I do agree that making asynchrony as explicit as possible is a good idea. Otherwise you end up with code like: async function foo(bar) { // ... } function nonObviousAsyncFn() { // ... return foo(quux); } Explicit return types would help, but most people don’t write them unless they’re forced by a linter.
- eurasiantiger 5y agoYes, this is a common anti-pattern return await foo();
- Aeolun 5y agoThis would still return a promise for both functions. My IDE at least is really obvious about what happens.