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
Yours
yield
后面跟的不是are
这个函数,而是are
执行后的返回值。其实它等于
yield undefined
, this is the reason for the error.Normal functions are not supported
Take a look
co
库的源码就好,报错是co
库报出来的,原因是因为楼上说的返回了undefined
, the specific error code is as follows:isPromise
检测是否为Promise
,co
库先尝试将yield
后转换为Promise
,具体参见toPromise
Function:was passed in
undefined
,所以最终toPromise
返回了undefined
,检测不是Promise
, so an error was thrown.As for why there is no output
1,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: