Javascript 代码中的'it'是什么?

Javascript 代码中的'it'是什么?,javascript,ecmascript-6,generator,Javascript,Ecmascript 6,Generator,我正在读下面的内容 他们在博客中有代码: function request(url) { // this is where we're hiding the asynchronicity, // away from the main code of our generator // `it.next(..)` is the generator's iterator-resume // call makeAjaxCall( url, function(res

我正在读下面的内容

他们在博客中有代码:

function request(url) {
    // this is where we're hiding the asynchronicity,
    // away from the main code of our generator
    // `it.next(..)` is the generator's iterator-resume
    // call
    makeAjaxCall( url, function(response){
        it.next( response );
    } );
    // Note: nothing returned here!
}
代码似乎很简单。但是在
makeAjaxCall
callback中,他们有一行名为
it.next(response)
。这是什么?我知道他们说它来自发电机,但我看不到它在任何地方被传递

但他们是这样做的:

function *main() {
    var result1 = yield request( "http://some.url.1" );
    var data = JSON.parse( result1 );

    var result2 = yield request( "http://some.url.2?id=" + data.id );
    var resp = JSON.parse( result2 );
    console.log( "The value you asked for: " + resp.value );
}
这句话是怎么说的:

var result1 = yield request( "http://some.url.1" );

如果在
请求
功能中未定义

是一个生成器,并且在您的博客文章的底部定义了它,则它可以工作:

var it = main();
it.next(); // get it all started

您在博客中提到的同一位作者,之前的一篇文章解释了ES6生成器的基本原理。你可以找到上一篇文章。关于你的问题,他在同一篇文章的第一段中这样定义:

function *foo() {
    yield 1;
    yield 2;
    yield 3;
    yield 4;
    yield 5;
}

var it = foo();

你应该读那篇文章,它一步一步地解释了一切:)

页面上的完整示例:

function request(url) {
    // this is where we're hiding the asynchronicity,
    // away from the main code of our generator
    // `it.next(..)` is the generator's iterator-resume
    // call
    makeAjaxCall( url, function(response){
        it.next( response );
    } );
    // Note: nothing returned here!
}

function *main() {
    var result1 = yield request( "http://some.url.1" );
    var data = JSON.parse( result1 );

    var result2 = yield request( "http://some.url.2?id=" + data.id );
    var resp = JSON.parse( result2 );
    console.log( "The value you asked for: " + resp.value );
}

var it = main();
it.next(); // get it all started
it
是一个
iterator
-(
main
函数)

参考链接关于

迭代器示例:

function makeIterator(array){
    var nextIndex = 0;

    return {
       next: function(){
           return nextIndex < array.length ?
               {value: array[nextIndex++], done: false} :
               {done: true};
       }
    }
}

var it = makeIterator(['yo', 'ya']);
console.log(it.next().value); // 'yo'
console.log(it.next().value); // 'ya'
console.log(it.next().done);  // true
函数生成迭代器(数组){
var-nextIndex=0;
返回{
下一步:函数(){
返回nextIndex
它是一个
迭代器
。您必须在其他地方定义了它。
//it。接下来(..)是生成器的迭代器resume//call
因此
它是生成器的迭代器
它在完全相同的代码块中定义<代码>变量it=main()@batman,是吗?