JS 생성기 주변에서 머리를 감싸려고하고 있지만 아래의 샘플 비동기 연산이 정의되지 않은 이유를 알 수 없습니다.ES6에서 생성기 함수 이해
수익의 전체 지점은 비동기 호출이 완료 될 때까지 대기하는 것이라고 생각했습니다.
function getUsers(){
\t var users;
\t $.ajax({
\t url: 'https://jsonplaceholder.typicode.com/users/'
\t }).then(function(users) {
\t console.log(gen.next(users));
\t });
\t
}
function getPosts(){
\t var posts;
\t $.ajax({
\t url: 'https://jsonplaceholder.typicode.com/posts/'
\t }).then(function(posts) {
\t console.log(gen.next(posts));
\t });
}
function getComments(){
\t var comments;
\t $.ajax({
\t url: 'https://jsonplaceholder.typicode.com/comments/'
\t }).then(function(comments) {
\t console.log(gen.next(comments));
\t });
}
function* myGenerator() {
\t var users = yield getUsers();
\t var posts = yield getPosts();
\t var comments = yield getComments();
\t 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>
사람은에 대해 어느 정도의 실마리를 제공 할 수 있습니까? 고맙습니다!
, 당신은 당신의 기능에서 아무것도 반환하지 것입니다. ('then()'을 반환하는 것은 동일하지 않습니다. –
언급 한 것처럼 아약스 함수에서 반환 할 수 없으며 일반적으로 콜백 함수라고하는 다른 함수를 호출해야합니다. 그렇지 않으면 약속의 세계에서 'resolve' 또는'reject'를 호출 할 필요가 있습니다 – Denno
@Mark_M과 당신의 의견을 보내 주셔서 감사합니다. 반환 된 데이터를 생성기로 다시 전달하는 여러 단계를 연결하고 시도하기 위해 위 코드를 편집했습니다. 첫 번째 두 yield 문은 여전히 정의되지 않은 상태로 반환됩니다. – rsilva