Sync from personal blog: www.52cik.com/2016/07/11/…

The previous article, “Making Generator Start itself”, described how to make Generator run with a starter. This article uses Async for more elegant asynchronous programming.

Start with examples

Let’s start with the example from the previous example.

function* gen() {
  var r1 = yield $.get('url1');
  var r2 = yield $.get('url2');
  var r3 = yield $.get('url3');

  console.log(r1, r2, r3);
}Copy the code

Then, we need to write an initiator to start the function. While using async writing, the code is:

async function gen() { var r1 = await $.get('url1'); var r2 = await $.get('url2'); var r3 = await $.get('url3'); console.log([r1, r2, r3].join('\n')); } gen(); // Run it directlyCopy the code

It runs directly, without the need for a writer, and the code simply changes to async and yield to await. So async is essentially a syntactic sugar for Generator.

multitasking

The catch with multitasking is that it cannot be handled directly in a forEach, map, or other method, otherwise it will report an error or get the wrong result.

function sleep(t) { return new Promise(resolve => setTimeout( _ => { resolve(+new Date) }, T))} async function run() {// order let a = await sleep(100) let b = await sleep(200 Promise.all([sleep(100), sleep(200), sleep(300)]) // let d = await promise.all ([100, 200), sleep(300)]) 300].map(t => sleep(t))) // let list = [sleep(100), sleep(200), sleep(300)] let e = [] for (let fn of list) { e.push(await fn) } console.log( '', 'a:', a, '\n', 'b:', b, '\n', 'c:', c, '\n', 'd:', d, '\n', 'e:', e, '\n' ) } run() // a: 1468317737179 // b: 1468317737384 // c: [ 1468317737485, 1468317737589, 1468317737688 ] // d: [ 1468317737792, 1468317737890, 1468317737989 ] // e: [1468317738094, 1468317738193, 1468317738293]Copy the code

summary

Async doesn’t change much, but is basically a syntactic sugar that lets us run generators without having to write our own starters. But it works really well, making asynchronous programming more synchronous.