My code is like this
const co = require('co');
function are(){
}
function* abc(){
var a = yield are()
console.log(1)
var b = yield are()
console.log(2)
var c = yield are()
console.log(3)
}
co(abc)
My expected execution result, the console should print out 1, 2, 3
But when executing, the program reported an error
should be said to be my yield
, which should be followed by function
, but in the demo above, my yield
is already followed by function
Why is there no expected output?
The second way of writing:
const co = require('co');
function are1(){
}
function are2(){
}
function are3(){
}
function* abc(){
var a = yield are1
console.log(1)
var b = yield are2
console.log(2)
var c = yield are3
console.log(3)
}
co(abc)
.then(data =>{
console.log(data)
})
.catch(err =>{
console.log(err)
})
co
has accepted a generator function. The above writing method cannot output 1, 2, and 3 on the console
漂亮男人2017-05-16 13:37:43
Yoursyield
后面跟的不是are
这个函数,而是are
执行后的返回值。
其实它等于yield undefined
, this is the reason for the error.
PHPz2017-05-16 13:37:43
Take a lookco
库的源码就好,报错是co
库报出来的,原因是因为楼上说的返回了undefined
, the specific error code is as follows:
if (value && isPromise(value))
return value.then(onFulfilled, onRejected);
return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
+ 'but the following object was passed: "' + String(ret.value) + '"'));
isPromise
检测是否为Promise
,co
库先尝试将yield
后转换为Promise
,具体参见toPromise
Function:
function toPromise(obj) {
if (!obj) return obj;
if (isPromise(obj)) return obj;
if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj);
if ('function' == typeof obj) return thunkToPromise.call(this, obj);
if (Array.isArray(obj)) return arrayToPromise.call(this, obj);
if (isObject(obj)) return objectToPromise.call(this, obj);
return obj;
}
was passed in undefined
,所以最终toPromise
返回了undefined
,检测不是Promise
, so an error was thrown.
As for why there is no output1,2,3
的原因,是因为yield
后面的关系,yield
后面是要接受函数作为参数,并且要执行这个函数的,所以yield
usually followed by an asynchronous operation, this function is the callback function, but that function, so just change it like this:
function are1(fn) {
fn();
}
function are2(fn) {
fn();
}
function are3(fn) {
fn();
}