es5、es6、es7 解决异步

es6 诞生之前,异步编程方式大概有 4 种

  • 回调函数
  • 事件监听
  • 发布订阅
  • promises 对象

es6 之前的 promises 对象是一种工作规范,es6 的 promise 是在此基础上,将众多 promises 规范写入语言标准

es5:回调函数

http1(function () {
    http2(function () {
        http3(function () {});
    });
});

es6:generator 和 yield

function* gen() {
    yield 'http1';
    yield 'http2';
    yield 'http3';
    return 'http4';
}
var g = gen();
console.log(g.next());
console.log(g.next());
console.log(g.next());
console.log(g.next());

es7:async 和 await,是 generator 语法糖

async function httpasync() {
    const f1 = await 'http1';
    const f2 = await 'http2';
    // return 的值会成为 then 方法回调函数的参数
    return [f1, f2];
}
httpasync().then(res => {
    console.log(res);
});
Last Updated:
Contributors: zhangfei