Skip to content

Instantly share code, notes, and snippets.

@crazybugliu
Created September 22, 2020 14:19
Show Gist options
  • Save crazybugliu/ca875e554459ecd71a0f4356c342cf06 to your computer and use it in GitHub Desktop.
Save crazybugliu/ca875e554459ecd71a0f4356c342cf06 to your computer and use it in GitHub Desktop.
async to generater
async function a(n) {
let c = 0;
let s = 0;
while (c < n) {
c += 1;
let x = await c; // c 也可以是其他 promise
s += x;
console.log(s);
}
return s
}
async function b() {
let v1 = await a(1);
let v2 = await a(2);
let v3 = await a(3);
let v4 = await a(4);
let v5 = await a(5);
let x = v1 + v2 + v3 + v4 + v5;
return x;
}
b().then(r => console.log(r));
function _asyncToGenerator(fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(function (value) {
step("next", value);
}, function (err) {
step("throw", err);
});
}
}
return step("next");
});
};
}
function* a(n) {
let c = 0;
let s = 0;
while (c < n) {
c += 1;
let x = yield c; // c 也可以是其他 promise()
s += x;
console.log(s);
}
return s
}
function* b() {
let v1 = yield ag(1);
let v2 = yield ag(2);
let v3 = yield ag(3);
let v4 = yield ag(4);
let v5 = yield ag(5);
let x = v1 + v2 + v3 + v4 + v5;
return x;
}
let ag = (() => {
let aG = _asyncToGenerator(a);
return function (n) {
let ag1 = aG.apply(this, arguments);
return ag1;
}
})();
let bg = (() => {
let bG = _asyncToGenerator(b);
return function () {
let ag1 = bG.apply();
return ag1;
}
})();
bg().then(r => {
console.log(r)
});
@crazybugliu
Copy link
Author

crazybugliu commented Sep 22, 2020

将 ES2017 中的 async/await 语法通过 babel 转换为 ES5 , 源码对比.

有助于理解 yield 生成器.

yarn add babel-preset-es2017 -D

.babelrc :

{
    "presets": [
        "es2017"
    ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment