node.js - 关于co用法的困惑
PHPz
PHPz 2017-04-17 15:29:26
0
2
608

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

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

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

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

PHPz
PHPz

学习是最好的投资!

reply all(2)
小葫芦

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

刘奇

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...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template