Recently, I was looking into some browser extension API's and noticed that it's very heavy on callbacks. It became apparent that people were aware of this, since in a newer version, they've made many of the methods provided async. Essentially transforming methods from
some.api.method(foo, bar, result => {
// do something
});
to
await result = some.api.method(foo, bar);
// do something
This is nice because it keeps things simple and readable, and things don't become a pyramid of indentation.
I realized this pattern is not just applicable to extension API's, but to any function with a callback. This gave me an idea; what if we had some syntax to create this without the need for the method itself to be async?
For example, instead of this
function asyncAPIMethod(foo, bar){
return new Promise(resolve => some.api.method(foo, bar, resolve));
}
what if we could just write this:
await some.api.method(foo, bar, %resolve);
(okay, maybe not write %resolve
, but this is just a demonstration of the idea).
This would open up quite some doors:
// wait until the document loads
await document.addEventListener('DOMContentLoaded', %resolve);
// wait 1 second
await setTimeout(%resolve, 1000);
// wait until my favorite image loads
await image.addEventListener('load', %resolve);
This would also mean we don't have to force an async API onto users, but users get to choose for themselves whether they want to await
our callback or if they want things to be synchronous.
Thoughts?