javaScript基础- */yield模拟async/await
async
function _async(promiseFunc) {
/*高阶函数只是为了不让他立即执行*/
return function () {
/*这是核心模块*/
return new Promise((resolve, reject) => {
/*获取迭代器*/
const generator = promiseFunc()
/*替开发者执行then操作 === 这是为什么async一定会返回promise的原因*/
const promise = generator.next().value
promise
.then((res) => {
/*完成then之后 === 执行then回调*/
generator.next(res);//把获取到的参数传出去
resolve(res);
})
.catch((err) => {
generator.next(err);
reject(err);
})
})
}
}
执行模块
/* 需要被执行模块 */
function getUserInfo() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("[CGS]")
}, 2000);
})
}
/* async/await示例 */
async function getDataAsync() {
const result = await getUserInfo()
console.log(result)
}
/* 使用自定义写的_async */
var testFunc = _async(function* getData() {
const result = yield getUserInfo()
console.log("_async result", result)
})
testFunc();