Trying to write a little chrome extension, which relies on the callback-heavy query functions of the chrome.*
interface, I quickly landed at promises and async/await, as I needed to guarantee the order of certain operations, while trying to avoid callback hell.
However, once I introduced async/await into some functions, every function that used them also had to be turned into an async function
in order to be able to await
the return value. Eventually even some global constants became promises, e.g.
const DEBUG = new Promise(function(resolve){
chrome.management.getSelf(resolve);
}).then(function(self){
return self.installType == 'development';
});
However, now I need to write await
everywhere and introducing weird bugs like if(DEBUG){...}
always being executed becomes way too easy.
While it seems possible to identify the errors using ESLINT, writing await
everywhere seems unnecessarily cumbersome and thus I was wondering if Javascript has some better construct that I am missing?
(Subjectively my current use of await/async seems backwards; Promises are kept as-is unless explicitly awaited, but it seems more desirable to me to have promises awaited by default in async functions and kept as bare promises only when explicitly requested.)
Promise.prototype.then()
statements i.e.new Promise(...).then(...).then(...)
– Forbearawait
s aPromise.all
with all asynchronously-loaded constants and only afterwards executes your main script. – Glamorousawait
sugar. – Glamorousconst x = await getX(); const y = await x.getY(); dostuff(x,y); ...
I'd be writinggetX().then(x => Promise.all([x, x.getY()])).then(([x,y]) => {dostuff(x,y); ...})
, which isn't any harder to forget doing, but if forgotten a lot harder to refactor. – Hypomaniaawait
statements everywhere; Hence the question about proper handling. – Hypomaniaasync/await
once you start the habbit. See "Pitfall 3" (Spoiler: you can treat the result of an async-function as a promise) – Obligor