How would I create a "data = xhrLoad(url)" function which is async inside but w/o .then or callback "hell"? I want xhrLoad to do Promise/Generator magic, but only return when the data is available.
Example:
data = initMyProgram(); // may call data = xhrLoad(url)
<use data here>
<more inline code here>
I realize Promises are wonderful, and .then/.catch are sophisticated .. but I want inline, sequential code .. not then-able code fragments that may not even be needed if the data is available w/o external resources.
Ex: In webgl programming, shaders can be in <scripts>
, in external files, in es6 modules, in es6 template strings, etc. I want to manage this by having xhr requests, if needed, magically be completed before initMyProgram returns.
While it's possible to do in ES6, it's not necessarily very convenient. But there are a couple of blog posts about it, it should be quite straightforward to follow them.
There is a proposal for
async/await
for ES7. Babel already supports.Note that
async/await
is just syntactic sugar for handling promises. Functions declared as async always return a promise, thus at the top level you still have to use the promise API.await
can only be used insideasync
functions, but anything that returns a promise can be awaited.Example:
Keep in mind that this is an experimental feature and the way it works may change over time.