【问题标题】:Async, waterfall issue异步,瀑布问题
【发布时间】:2020-09-06 02:20:50
【问题描述】:

我在这里尝试检索所有对象并将它们推送到json 文件中。由于某种原因,只有一条记录被推入文件中,而它应该包含更多对象。甚至在执行之前就已发送响应。你能帮我解决这个问题还是让我知道我哪里出错了?这是我的代码:

exports.createjoson = (req, res) => {
  const Responsearray = [];
  async.waterfall(
    [
      function(waterfallCb) {
        //  ... first function
      },
      function(results, waterfallCb1) {
        //second function
        async.eachLimit(
          results,
          100,
          function(singleResult, eachCallback) {
            async.waterfall(
              [
                async function(innerWaterfallCb) {
                  try {
                    NewsModel.find(
                      { _id: singleResult.newsId }, // #individual article
                      async (err, newsResult) => {
                        if (err) {
                          return innerWaterfallCb(
                            // #displaying error
                            "error in fetching news data"
                          );
                        }
                        const map = new Map();
                        for (const item of newsResult) {
                          if (!map.has(item.source)) {
                            map.set(item.source, true);
                            Response = {
                              newsId: item._id,
                              title: item.title,
                              comment: singleResult.comment
                            };
                          }
                        }
                        resPond = await Response;
                        Responsearray.push(resPond);
                        let data = JSON.stringify(Responsearray);
                        await fs.writeFileSync("abc.json", data);
                      }
                    );
                  } catch (error) {
                    innerWaterfallCb(error);
                  }
                }
              ],
              function(err) {
                if (err) {
                  return eachCallback(err);
                }

                eachCallback(null);
              }
            );
          },
          function(err) {
            if (err) {
              return waterfallCb1(err);
            }

            waterfallCb1(null);
          }
        );
      }
    ],
    function(err) {
      if (err) {
        return res.status(200).json({ status: "400", message: err });
      }
      res.status(200).json({ status: "200", message: "success" });
    }
  );
};

【问题讨论】:

    标签: javascript node.js json asynchronous async-await


    【解决方案1】:

    代码有很多问题:

    1. fs.writeFileSync 将覆盖文件,而不是附加到它,因此只有您写入的最后一个数据将在abc.json 中。它也不会返回Promise,因此无需在其上使用await。它同步运行,因此在完成之前不会返回(这就是函数名称中的Sync 的含义)。要追加而不是覆盖文件,可以将标志选项设置为“a”以追加(默认为“w”)。

    2. 似乎没有在任何地方调用返回 innerWaterfallCb(null) - 仅在错误情况下。内部瀑布函数不应标记为async,因为它实际上不需要进行任何await 调用。但是你应该在文件写入之后调用return innerWaterfallCb(null)

    3. 最好只收集responseArray 中的数据并在外部瀑布的末尾写入一次文件,而不是在内部瀑布的深处重复写入。

    4. 变量应该以小写字母开头(比如responseArray而不是ResponseArray,因为大写的首字母通常表示类或模块。

    5. 不要将async/await 与异步模块(瀑布和eachLimit)混用。如果您使用的是正确的 Promises 和 async/await,那么应该不需要使用 async 模块。完全删除waterfall 的使用并重写以正确使用Promise 对象会更干净。

    【讨论】:

    • 谢谢,我用 promises 重写了代码。现在我面临的问题是所有对象都被推送到数组中,但我无法将其写入文件
    • 会发生什么?我假设你 stringify 然后像以前一样将该字符串写入文件
    • 在我对 api 进行更改后,我发布了另一个关于相同的问题。你能看看吗?
    猜你喜欢
    • 2018-10-28
    • 2019-10-17
    • 2018-11-13
    • 2015-09-03
    • 2015-07-18
    • 2015-04-28
    • 1970-01-01
    • 2019-01-02
    • 2020-10-13
    相关资源
    最近更新 更多