search

Home  >  Q&A  >  body text

node.js - 关于co用法的困惑

node小白,今天学习了下用Node写命令行工具。

然后有个TJ大神写的co包:

    co(function* (){
        yield setTimeout(function() {
            console.log(1);
        }, 5);
        
        yield setTimeout(function() {
            console.log(2);
        }, 1);
    });

最后这段代码执行的时候只输出了1。为什么没有输出2呢?

PHPzPHPz2777 days ago566

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 15:31:26

    Your usage does not comply with the specification. Co allows yielding a promise, generator, array, and object, but does not allow yielding an ordinary function. It must be a paradigm function;
    When yielding the first setTimeout, the function executes normally. , but an error is reported after execution:

    TypeError: You may only yield a function, promise, generator, array, or object, but the following object was passed: "[object Object]"

    The error report will naturally be interrupted, so the code will not continue to execute. As for why you know the above error is reported, it will be clear when you read the source code carefully

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 15:31:26

    tj/co is not perfect, you can use co in hprose instead of tj/co, here is an introduction article:

    https://segmentfault.com/a/11...

    reply
    0
  • Cancelreply