异步回调未正确调用

时间:2017-06-14 13:05:10

标签: javascript node.js

triviaCtrl.answer = function(req, res) {
  //console.log(req.query.name);
  var data = {};
  var pointdata = {};
  var datas = {
    "Status": 0,
    "Message": ""
  };
  return new Promise((resolve, reject) => {
    var newAnswer = function(cb) {
      data.questionId = req.query.questionId;
      data.userId = req.query.userId;
      data.correctAnswer = req.query.correctAnswer;
      data.userAnswer = req.query.userAnswer;
      data.type = req.query.type;
      data.point = req.query.point;
      Answer.create(data, cb);
    }
    var checkuserpoint = function(cb) {
      Point.findOne({
        userId: req.query.userId
      }, function(err, result, cb) {
        if (result) {
          result.availablePoint = Number(result.availablePoint) + Number(req.query.point);
          result.totalWinPoint = Number(result.totalWinPoint) + Number(req.query.point);
          result.save(cb);
        } else {
          pointdata.userId = req.query.userId;
          pointdata.totalWinPoint = req.query.point;
          pointdata.redeemPoint = 0;
          pointdata.availablePoint = req.query.point;
          Point.create(pointdata, cb);
        }
      });
    }

    async.waterfall([newAnswer, checkuserpoint], function(err, result) {
      if (err) {
        //reject(err);
        datas["Status"] = 0;
        datas["Message"] = err;
        res.json(datas);
      } else {
        datas["Status"] = 1;
        datas["Message"] = result;
        res.json(datas);
      }
    });
  });
}

如果我删除" newAnswer,checkuserpoint"一个功能从那里开始工作但是当我同时使用它们时它不会给出任何响应。但功能正常工作

1 个答案:

答案 0 :(得分:0)

async.waterfall中的第二个和更多函数将参数传递给之前的函数回调

在第二个功能中查看arg1arg2

async.waterfall([
    function(callback) {
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback) {
        // arg1 now equals 'one' and arg2 now equals 'two'
        callback(null, 'three');
    },
    function(arg1, callback) {
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
    // result now equals 'done'
});