How Load xmlHttpRequest resources inline/sequentially with ES6 Promises & Generators?

363 views Asked by At

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.

1

There are 1 answers

1
Felix Kling On BEST ANSWER

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 inside async functions, but anything that returns a promise can be awaited.

Example:

function foo() {
  return new Promise(resolve => {
    setTimeout(() => resolve(42), 3000);
 });
}

async function bar() {
  let answer = await foo();
  console.log(answer);
  return answer * 2;
}

bar().then(result => console.log(result));

Keep in mind that this is an experimental feature and the way it works may change over time.