即使在调用“return callback()”之后,Nodejs函数仍会继续执行

时间:2018-02-14 11:58:46

标签: javascript node.js asynchronous callback

在下面的函数中,我理解代码应该在回调之后停止执行,如果满足前两个if条件中的任何一个,即如果“validate_post”返回错误或者“!clean.postId ==真正”。当我在测试期间遇到第二个if条件时,使用错误消息调用回调,但是仍然执行了以下块(data.updatePost()),导致再次调用回调。我在这做错了什么?谢谢你的帮助!

    var data = require('./data')
    var validate_post = require('./validate_post')

    module.exports = function(post, callback) {
      validate_post(post, function(err, clean) {
        if(err) {
          callback({status: "error", message: err})
          return
        }

        if(!clean.postId) {
          console.log('first callback is called at this point')
          callback({status: "error", message: "Something is off here"})
          return
        }

        console.log('code still executes for some reason')
        data.updatePost(clean.postId, clean.post, function(err, res) {
          if (err) {
            callback({status: "error", message: err})
            return
          }
          console.log('callback is called a second time at this point')
          callback(null, {status: "success", message: res})
        })
      })
    }

1 个答案:

答案 0 :(得分:0)

事实证明,我忘了在validate_post()函数中放置一个return语句,导致validate_post()的回调被触发两次。修复validate_post()函数后,我的问题现在得到了解决。谢谢!

相关问题