javascript - 缓存异步函数的结果,并将其传递给 Async.js 中的下一个函数

标签 javascript node.js asynchronous async.js

这几天我一直在努力完成following,但就是解决不了。我觉得我已经尝试了一切。所以这里...

我的路线有一个 JSON 对象,其中包含创建新测验的所有信息。 换句话说 - 一个对象,其中包含有关新测验的信息,一组问题,其中每个问题都包含一组答案。

我使用 async.js waterfall 函数,并希望执行以下操作:

  • 将新测验保存到数据库,并将从数据库返回的新测验 ID 传递给下一个 waterfall 函数

  • 遍历每个问题。缓存从数据库返回的新问题 ID,并将它们传递给下一个 waterfall 函数。这里的问题是缓存 ID。由于该函数是异步的,我无法将结果缓存到任何地方以供下一个函数使用...

  • 遍历每个答案,并将它们保存到数据库

这是我得到的:

router.post('/quiz/create', function (req, res) {
    // JSON object with the new Quiz
    var json = req.body;
    async.waterfall([
        function(callback) {
            // Returns a Quiz ID for the new quiz, and passes it to the next waterfall function
            db.createQuiz(json, function(err, result) {
                // ID returned from DB is formatted as [{'': id}], hence result[0]['']
                callback(null, result[0]['']);
            });
        },
        function(quizID, callback) {
            // Loop through each question in the quiz
            async.forEachSeries(json.questions, function(question, callback) {
               // Save the question to DB, and get the new question ID returned
               db.createQuestion(question, quizID, function(err, result) {
                   // TODO: cache the new question ID's in an array somewhere to be passed to the next waterfall function
                   // Start next iteration of the loop
                   callback();
               });
            }, function(err) {
                // Done with all questions. Pass question ID's to next function
                callback(null, cachedQuestionIDs);
            });
        },
        function(cachedQuestionIDs, callback) {
            // TODO: access the question ID's, and use them to loop through and save answers to DB
        }
    ], function(err, result) {
        res.json({
           success: true,
           message: 'Quiz created!'
       });
    });
});

最佳答案

只需将值存储在 async.forEachSeries() 之外但在 async.waterfall() 控制流中的包装第二个函数内的数组中。然后,您可以在 async.forEachSeries() 执行完毕后返回此数组。

function(quizID, callback) {
  var cachedQuestionIDs = [];

  // Loop through each question in the quiz
  async.forEachSeries(json.questions, function(question, callback) {
    // Save the question to DB, and get the new question ID returned
    db.createQuestion(question, quizID, function(err, result) {
      // Store our result
      cachedQuestionIDs.push(result);

      // Start next iteration of the loop
      return callback();
    });
  }, function(err) {
    // Done with all questions. Pass question ID's to next function
    return callback(null, cachedQuestionIDs);
  });
}

关于javascript - 缓存异步函数的结果,并将其传递给 Async.js 中的下一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35366167/

相关文章:

node.js - 如何更改firebase云函数中的显示名称?

javascript - 如何在没有 alpha 堆叠的情况下在 globalAlpha < 1 的 Canvas 上绘制多个元素?

javascript - 不可变的 js map 人口

javascript - 比较js中的两个字符串并找出差异

node.js - Gruntjs - 以特定顺序运行多个阻塞任务(Mongo 和 Node.js)

python - 在 RQ 中重试失败的作业

javascript - VueJS 从方法访问模型

javascript - Browserify多次解析同一个文件

JavaScript/JQuery : Best way to avoid nesting of asynchronous functions/anonymous callback functions

c++ - std::async 函数串行运行