我试图围绕JS生成器,但是我不明白为什么下面的示例异步操作返回未定义。
我认为收益的全部目的是等待异步调用完成。
function getUsers(){
var users;
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users/'
}).then(function(users) {
console.log(gen.next(users));
});
}
function getPosts(){
var posts;
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/'
}).then(function(posts) {
console.log(gen.next(posts));
});
}
function getComments(){
var comments;
$.ajax({
url: 'https://jsonplaceholder.typicode.com/comments/'
}).then(function(comments) {
console.log(gen.next(comments));
});
}
function* myGenerator() {
var users = yield getUsers();
var posts = yield getPosts();
var comments = yield getComments();
return ([users, posts, comments]);
}
var gen = myGenerator();
gen.next();
// {value: undefined, done: false} ---> why undefined here?
// {value: undefined, done: false} ---> why undefined here?
// {value: Array(3), done: true} ---> YAY, array DOES contains expected data
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
谁能对此有所启发?谢谢!
因此,与编辑工作有点不同。除最后一种情况外,在每种情况下,生成器都会产生未定义函数的结果,因为函数不会返回任何内容。
但是,当您next()
从then()
s内部调用时,您会将ajax promise的结果传递给生成器。发生器接收值,并保存在变量(users
,posts
等)。但是它仍然返回未定义,因为yield getPosts()
函数的值不返回任何值,所以的值是未定义的。
对的最后一次调用next()
发生在的then()
中getComments()
。现在,生成器的值已用完,因此它会返回,{done: true}
并且您已经异步地将值放入变量中。它返回那些和您完成的操作。
如果您这样做,这一切都将更加容易:
function getUsers(){
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/users/'
})
}
getUsers().then(console.log)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句