本文就是簡單介紹下 Async 語法編譯後的代碼。git
const fetchData = (data) => new Promise((resolve) => setTimeout(resolve, 1000, data + 1))
const fetchValue = async function () {
var value1 = await fetchData(1);
var value2 = await fetchData(value1);
var value3 = await fetchData(value2);
console.log(value3)
};
fetchValue();
// 大約 3s 後輸出 4
複製代碼
咱們直接在 Babel 官網的 Try it out 粘貼上述代碼,而後查看代碼編譯成什麼樣子:github
"use strict";
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");
});
};
}
var fetchData = function fetchData(data) {
return new Promise(function(resolve) {
return setTimeout(resolve, 1000, data + 1);
});
};
var fetchValue = (function() {
var _ref = _asyncToGenerator(
/*#__PURE__*/ regeneratorRuntime.mark(function _callee() {
var value1, value2, value3;
return regeneratorRuntime.wrap(
function _callee$(_context) {
while (1) {
switch ((_context.prev = _context.next)) {
case 0:
_context.next = 2;
return fetchData(1);
case 2:
value1 = _context.sent;
_context.next = 5;
return fetchData(value1);
case 5:
value2 = _context.sent;
_context.next = 8;
return fetchData(value2);
case 8:
value3 = _context.sent;
console.log(value3);
case 10:
case "end":
return _context.stop();
}
}
},
_callee,
this
);
})
);
return function fetchValue() {
return _ref.apply(this, arguments);
};
})();
fetchValue();
複製代碼
regeneratorRuntime 相關的代碼咱們在 《ES6 系列之 Babel 將 Generator 編譯成了什麼樣子》 中已經介紹過了,此次咱們重點來看看 _asyncToGenerator 函數:babel
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");
});
};
}
複製代碼
以上這段代碼主要是用來實現 generator 的自動執行以及返回 Promise。app
當咱們執行 fetchValue()
的時候,執行的其實就是 _asyncToGenerator
返回的這個匿名函數,在匿名函數中,咱們執行了異步
var gen = fn.apply(this, arguments);
複製代碼
這一步就至關於執行 Generator 函數,舉個例子:async
function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
var hw = helloWorldGenerator();
複製代碼
var gen = fn.apply(this, arguments)
就至關於 var hw = helloWorldGenerator();
,返回的 gen 是一個具備 next()、throw()、return() 方法的對象。函數
而後咱們返回了一個 Promise 對象,在 Promise 中,咱們執行了 step("next"),step 函數中會執行:fetch
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
複製代碼
step("next") 就至關於 var info = gen.next()
,返回的 info 對象是一個具備 value 和 done 屬性的對象:ui
{value: Promise, done: false}
複製代碼
接下來又會執行:this
if (info.done) {
resolve(value);
} else {
return Promise.resolve(value).then(
function(value) {
step("next", value);
},
function(err) {
step("throw", err);
}
);
}
複製代碼
value 此時是一個 Promise,Promise.resolve(value) 依然會返回這個 Promise,咱們給這個 Promise 添加了一個 then 函數,用於在 Promise 有結果時執行,有結果時又會執行 step("next", value)
,從而使得 Generator 繼續執行,直到 info.done
爲 true,纔會 resolve(value)
。
(function() {
var ContinueSentinel = {};
var mark = function(genFun) {
var generator = Object.create({
next: function(arg) {
return this._invoke("next", arg);
}
});
genFun.prototype = generator;
return genFun;
};
function wrap(innerFn, outerFn, self) {
var generator = Object.create(outerFn.prototype);
var context = {
done: false,
method: "next",
next: 0,
prev: 0,
sent: undefined,
abrupt: function(type, arg) {
var record = {};
record.type = type;
record.arg = arg;
return this.complete(record);
},
complete: function(record, afterLoc) {
if (record.type === "return") {
this.rval = this.arg = record.arg;
this.method = "return";
this.next = "end";
}
return ContinueSentinel;
},
stop: function() {
this.done = true;
return this.rval;
}
};
generator._invoke = makeInvokeMethod(innerFn, context);
return generator;
}
function makeInvokeMethod(innerFn, context) {
var state = "start";
return function invoke(method, arg) {
if (state === "completed") {
return { value: undefined, done: true };
}
context.method = method;
context.arg = arg;
while (true) {
state = "executing";
if (context.method === "next") {
context.sent = context._sent = context.arg;
}
var record = {
type: "normal",
arg: innerFn.call(self, context)
};
if (record.type === "normal") {
state = context.done ? "completed" : "yield";
if (record.arg === ContinueSentinel) {
continue;
}
return {
value: record.arg,
done: context.done
};
}
}
};
}
window.regeneratorRuntime = {};
regeneratorRuntime.wrap = wrap;
regeneratorRuntime.mark = mark;
})();
"use strict";
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");
});
};
}
var fetchData = function fetchData(data) {
return new Promise(function(resolve) {
return setTimeout(resolve, 1000, data + 1);
});
};
var fetchValue = (function() {
var _ref = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee() {
var value1, value2, value3;
return regeneratorRuntime.wrap(
function _callee$(_context) {
while (1) {
switch ((_context.prev = _context.next)) {
case 0:
_context.next = 2;
return fetchData(1);
case 2:
value1 = _context.sent;
_context.next = 5;
return fetchData(value1);
case 5:
value2 = _context.sent;
_context.next = 8;
return fetchData(value2);
case 8:
value3 = _context.sent;
console.log(value3);
case 10:
case "end":
return _context.stop();
}
}
},
_callee,
this
);
})
);
return function fetchValue() {
return _ref.apply(this, arguments);
};
})();
fetchValue();
複製代碼
請原諒我水了一篇文章……
ES6 系列目錄地址:github.com/mqyqingfeng…
ES6 系列預計寫二十篇左右,旨在加深 ES6 部分知識點的理解,重點講解塊級做用域、標籤模板、箭頭函數、Symbol、Set、Map 以及 Promise 的模擬實現、模塊加載方案、異步處理等內容。
若是有錯誤或者不嚴謹的地方,請務必給予指正,十分感謝。若是喜歡或者有所啓發,歡迎 star,對做者也是一種鼓勵。