在这里,我正在尝试检索所有对象并将它们推送到文件中。由于某种原因,当一条记录应包含更多对象时,只有一条记录被推送到文件中。甚至在执行之前就发送了响应。你能帮我解决这个问题,或者让我知道我哪里错了吗?这是我的代码:jsonexports.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); } } ],
1 回答
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
该代码存在许多问题:
fs.writeFileSync将覆盖文件,而不是附加到该文件,因此只有您写入的最后一个数据才会在 .此外,它不会返回 a,因此无需在其上使用。它同步运行,因此在完成之前不会返回(这就是其函数名称中的含义)。若要追加而不是覆盖文件,可以将标志选项设置为“a”以追加(默认值为“w”)。abc.jsonPromiseawaitSync似乎没有调用返回任何地方 - 仅在错误情况下。内部瀑布函数不应该被标记,因为它不需要真正做任何调用。但是您应该在写入文件后调用。
innerWaterfallCb(null)asyncawaitreturn innerWaterfallCb(null)最好只是在外部瀑布的末尾收集数据并写入文件一次,而不是在内部瀑布的深处重复写入文件。
responseArray变量应以小写字母开头(例如,因为大写的首字母通常表示类或模块。
responseArrayResponseArray不要与异步模块(瀑布和每个Limit)混合使用。如果您使用的是正确的 Promises,那么就没有必要使用异步模块。完全删除的使用并重写以正确使用对象会更干净。
async/awaitasync/awaitwaterfallPromise
添加回答
举报
0/150
提交
取消
