In Node.js, how do I chain asynchronous functions

2019-08-06 04:28发布

Today I have been playing with @substack's node-seq module, it allows me to chain together async functions.

https://github.com/substack/node-seq

I got it working with parallel functions, but having trouble running functions sequentially. Whenever I run the following code, it only prints out the 'hello1' statement. Any ideas what I'm doing wrong?

var Seq = require('seq');

Seq()
    .seq(function () {
        console.log('hello1');
    })
    .seq(function () {
        console.log('hello2');
    })
;

Thanks for any suggestions!

1条回答
ら.Afraid
2楼-- · 2019-08-06 04:45

You just need to read the documentation

Each method executes callbacks with a context (its this) described in the next section. Every method returns this.

Whenever this() is called with a non-falsy first argument, the error value propagates down to the first catch it sees, skipping over all actions in between. There is an implicit catch at the end of all chains that prints the error stack if available and otherwise just prints the error.

this should solve your problem.

var Seq = require('seq');

Seq()
    .seq(function () {
        console.log('hello1');
        this();
    })
    .seq(function () {
        console.log('hello2');
    })
;

Otherwise Seq has no way of knowing when the step is done.

查看更多
登录 后发表回答