您的位置:首页 > 其它

es6 在迭代器中获取异步的值

2016-07-08 10:49 260 查看
由于迭代器在主线程中运行,所以我们普通

yield xxx   // xxx属于一个异步操作,所以正常情况下下一个yield不同被上一个yield同步,

为了使下一个yield与上一个yield同步,我们必须把迭代器带入xxx的异步环境中,或者通过同步的方式做到,可能你还不知道我在说什么,下面我细说

 


所以无法王成两个yield的同步操作,下面我们完成同步操作,就是把yield2的操作在子线程王成



例子:

function Main2(fn){

const iter = fn();
const async = iter.next();

async.value.then((data) => {
iter.next(data);
});
}

const list = Main2(function *(){
// showLoadingScreen();
console.log('loading...');
let data;
const dd = yield asyncTask3(function(json){

data = json;
console.log('...', data);
});
console.log('finish...',dd);
return dd;
});


注意的是我们把整个迭代器带入子线程中了!!!!!!

loading...

main-list.js?0e37:180finish2...

main-list.js?0e37:145Object {value: Promise, done: false}

main-list.js?0e37:192parsed data undefined
main-list.js?0e37:175 ... [Object, Object, Object, Object, Object]

main-list.js?0e37:177finish... [Object, Object, Object, Object, Object]

main-list.js?0e37:109 parsed json [Object, Object, Object, Object, Object]

看看上面的三个log同步把!!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: