async函数转为 generator 函数,并放入co自执行函数中运行,await就相当于generator函数中的 yield 执行器,执行一次promise 返回{value, done}
function yieldPromise(generator){
var iterator=generator();
recursiveCore.call(iterator);
}
function recursiveCore(feedback){
var iterator=this,
result=iterator.next(feedback);
if(result.done){
return;
}
var promise=result.value;
Promise.resolve(promise).then(function(v){
recursiveCore.call(iterator,v);
});
}
yieldPromise(function*(){
var v1=yield new Promise(function(resolve,reject){
setTimeout(function(){
resolve('Hello');
},1500);
});
console.warn(v1);
var v2=yield new Promise(function(resolve,reject){
setTimeout(function(){
resolve('World');
},1500);
});
console.warn(v2);
});
function yeildPromise(gen) {
const iterator = gen()
const next = data => {
const { done, value } = iterator.next(data);
if(done) return value;
value.then(data => next(data))
}
next();
}
function asyncToGenerator(generatorFunc) {
return function() {
const gen = generatorFunc.apply(this, arguments)
return new Promise((resolve, reject) => {
function step(key, arg) {
let generatorResult
try {
generatorResult = gen[key](arg)
} catch (error) {
return reject(error)
}
const { value, done } = generatorResult
if (done) {
return resolve(value)
} else {
return Promise.resolve(value).then(val => step('next', val), err => step('throw', err))
}
}
step("next")
})
}
}
const obj = {a: 'a1', b: 'b1', c: 'c1'};
// typeof obj[Symbol.iterator] // 'undefined'
//
// for (const val of obj) {
// console.log(val);
// }
// VM974:4 Uncaught TypeError: obj is not iterable
obj[Symbol.iterator] = function() {
const self = this;
const keys = Object.keys(this);
const len = keys.length;
let pointer = 0;
return {
next() {
const done = pointer >= len;
console.log('----', keys);
const value = !done ? self[keys[pointer++]] : undefined;
return {
value,
done
};
}
}
}
for (const val of obj) {
console.log('val', val);
}
// 'a1'
// 'b1'
// 'c1'