回调未等待函数完成执行

问题描述 投票:0回答:1

我有一个回调函数,该函数从数据库返回一个对象。但是,在我的async.waterfall中,函数“外部”不等待对象完全加载,这意味着传入时它是未定义的。这意味着我的最终错误是TypeError: Cannot read property 'replace' of undefined。我在做什么错?

function loadModelInstance (name, callback) {
  Model.findOne({ name: name }, function (_err, result) {
    if (result) {

      return callback(_err, result.content)
    } 
  })
}

function generatedNow (modelInstance) {
  generatedKeys = generatedKeys.concat(getAllMatches(generatedRegexp, modelInstance.replace(/(\n|\r)/g, '')));
}

async.waterfall(
    [
      function loadTemplate (wfaCallback) {
        loadModelInstance(name, function (_err, modelInstance) {
          wfaCallback(_err, modelInstance)
        })
      },

      function external (modelInstance, wfaCallback) {
        generatedNow(tracking, message, modelInstance, placeholders, function (err, updatedPlaceholders) {
        })
      },
    ],
    function (err) {
        // Node.js and JavaScript Rock!
    }
);
javascript asynchronous callback
1个回答
0
投票

请您提供更多详细信息。您在哪里调用“ generateNow”函数。我看不到函数调用“ generateNow”。

好像您没有正确使用参数顺序。下面的代码应该可以工作。

async.waterfall(
  [
    function loadTemplate(wfaCallback) {
      loadModelInstance(name, function(_err, modelInstance) {
        wfaCallback(_err, modelInstance);
      });
    },

    function external(err, modelInstance, wfaCallback) {
      generatedNow(modelInstance, tracking, message, placeholders, function(
        err,
        updatedPlaceholders
      ) {});
    }
  ],
  function(err) {
    // Node.js and JavaScript Rock!
  }
);
© www.soinside.com 2019 - 2024. All rights reserved.