node.js - nodejs's co module self-executes yield
伊谢尔伦
伊谢尔伦 2017-05-16 13:35:43
0
4
687

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

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(4)
漂亮男人

Yoursyield后面跟的不是are这个函数,而是are执行后的返回值。
其实它等于yield undefined, this is the reason for the error.

某草草
function* are(){

}
伊谢尔伦

Normal functions are not supported

PHPzhong

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检测是否为Promiseco库先尝试将yield后转换为Promise,具体参见toPromiseFunction:

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后面是要接受函数作为参数,并且要执行这个函数的,所以yieldusually 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();
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template