ES6发生器 - 他们真的是异步/等待的替代品吗? [英] ES6 generators- are they really an alternative to async/await?
问题描述
此 typescript博客文章说:
One of the posts in the comments section of this typescript blog post says:
如果我必须等到2.0为ES6发电机支持,我只需要
粘贴Traceur。发电机是一件很大的事情,他们使用诸如Koa,Co,Bluebird,
等的图书馆给你
async / await支持
Async / await关键字将允许应用程序保留类似于同步代码的逻辑结构。如何使用发电机来完成类似的事情?例如,如何将生成器与ajax调用结合使用以产生避免使用回调的同步样式代码?
Async/await keywords would allow applications to retain a logical structure that resembles synchronous code. How would one use a generator to accomplish something similar? For example, how would you use a generator in conjunction with an ajax call to produce synchronous style code that avoids using callbacks?
推荐答案
你只需要用一个帮助函数来抽象。
You just have to abstract that with an helper function.
假设jQuery:
function ajax(type, url, data){
$.ajax({
url: url,
data: data,
type: type
})
.done(function(data) {
iterator.next(data);
})
.fail(function() {
iterator.throw();
});
}
var get = ajax.bind(null, 'GET');
var post = ajax.bind(null, 'POST');
var put = ajax.bind(null, 'PUT');
var patch = ajax.bind(null, 'PATCH');
var del = ajax.bind(null, 'DELETE');
function *asyncGet() {
var URL = 'https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow'
var data = yield get(URL);
console.log(data);
}
var iterator = asyncGet();
iterator.next();
另一个使用 setTimeout
的示例:
function delayReturn(time, val){
setTimeout(function(){
iterator.next(val);
}, time);
}
var delayReturn1s = delayReturn.bind(null, 1000);
function *main() {
console.log(yield delayReturn1s('Lolcat'));
}
var iterator = main();
iterator.next()
当然,您可以抽象出这样的迭代器传递:
Of course you can abstract the iterator passing with something like this:
var async = function(generator){
var resume = function(err, data){
if (err) iterator.throw();
iterator.next(data);
}
var iterator = generator(resume);
iterator.next();
}
然后你可以简单地:
function ajax(type, url, data, cb){
$.ajax({
url: url,
data: data,
type: type
})
.done(function(data) {
cb(null, data)
})
.fail(function() {
cb(arguments);
});
}
var get = ajax.bind(null, 'GET');
var post = ajax.bind(null, 'POST');
var put = ajax.bind(null, 'PUT');
var patch = ajax.bind(null, 'PATCH');
var del = ajax.bind(null, 'DELETE');
async(function *(resume) {
var URL = 'https://api.stackexchange.com/2.2/answers?order=desc&sort=activity&site=stackoverflow'
var data = yield get(URL, null, resume);
console.log(data);
});
这篇关于ES6发生器 - 他们真的是异步/等待的替代品吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!