Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign up阿里&字节:手写 async/await 的实现 #56
Comments
|
之前看过一篇不错的,看看顺便默写下代码 function asyncToGen(genFunction) {
return function (...args) {
const gen = genFunction.apply(this, args);
return new Promise((resolve, reject) => {
function step(key, arg) {
let genResult;
try {
genResult = gen[key](arg);
} catch (err) {
return reject(err);
}
const { value, done } = genResult;
if (done) {
return resolve(value);
}
return Promise.resolve(value).then(
(val) => {
step('next', val);
},
(err) => {
step('throw', err);
},
);
}
step('next');
});
};
}
const getData = () => new Promise(resolve => setTimeout(() => resolve('data'), 1000));
function* testG() {
const data = yield getData();
console.log('data: ', data);
const data2 = yield getData();
console.log('data2: ', data2);
return 'success';
}
const gen = asyncToGen(testG);
gen().then(res => console.log(res)); |
|
本质是希望实现一个co函数 let delay = function (time, fnc) {
setTimeout(() => {
fnc(time);
}, time);
}
let promisefy = (fn) => {
return (...arg) => {
return new Promise ((resolve, reject)=> {
fn(...arg, (param)=>{
resolve(param);
})
});
}
}
let delayP = promisefy(delay);
const gen = function* () {
const ret1 = yield delayP(1000);
console.log(ret1);
const ret2 = yield delayP(2000);
console.log(ret2);
}
// 阴间写法
const g = gen();
g.next().value.then((res1)=>{
g.next(res1).value.then((res2)=>{
//
});
})
// 正常写法
function co (generator) {
return new Promise((resolve, reject)=>{
const gen = generator();
function next (...param) {
let tmp = gen.next(...param);
if (tmp.done) {
resolve(tmp.value);
return;
}
tmp.value.then((...ret)=>{
next(...ret);
})
}
next();
})
}
co(gen).then((res)=>{
console.log(res);
}) |

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.

No description provided.