Node.js: How to run asynchronous code sequentially

前端 未结 6 2037
眼角桃花
眼角桃花 2021-01-03 02:37

I have this chunk of code

User.find({}, function(err, users) {
    for (var i = 0; i < users.length; i++) {
        pseudocode
        Friend.find({
              


        
6条回答
  •  走了就别回头了
    2021-01-03 03:20

    I prefer the promise module to q https://www.npmjs.com/package/promise because of its simplicity

    var Promises = require('promise');
    var promise = new Promises(function (resolve, reject) {
        // do some async stuff
        if (success) {
            resolve(data);
        } else {
            reject(reason);
        }
    });
    promise.then(function (data) {
        // function called when first promise returned
        return new Promises(function (resolve, reject) {
            // second async stuff
            if (success) {
                resolve(data);
            } else {
                reject(reason);
            }
        });
    }, function (reason) {
        // error handler
    }).then(function (data) {
        // second success handler
    }, function (reason) {
        // second error handler
    }).then(function (data) {
        // third success handler
    }, function (reason) {
        // third error handler
    });
    

    As you can see, you can continue like this forever. You can also return simple values instead of promises from the async handlers and then these will simply be passed to the then callback.

提交回复
热议问题