我正在阅读以下blog。
他们在博客中有代码:
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
回调中,他们有一行名为it.next(response)
。这是it
的内容是什么?我知道他们正在告诉它来自发电机,但我不认为它会被传递到任何地方!
但他们这样做:
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" );
如果在it
函数中未定义request
,则有效吗?
答案 0 :(得分:0)
var connObj=require('../Routes/connection.js');
var connection=connObj.connExport();
exports.getIndivRecords= function(req, res, next){
res.send({
Result: connection+"This is result"
});
return next();
};
是一个生成器,它在您的博客文章底部定义:
it
答案 1 :(得分:0)
您所说的博客中的同一位作者,有一篇文章解释了ES6 Generators的基础知识。您可以找到上一篇文章here。关于你的问题,他在同一篇文章中定义了这样的第一段:
function *foo() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}
var it = foo();
你应该阅读那篇文章,它一步一步解释所有内容:)
答案 2 :(得分:0)
页面上的完整示例:
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
函数)。
关于Iterators and generators的参考链接。
关于迭代器的示例:
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