如何等待所有异步调用完成

编程入门 行业动态 更新时间:2024-10-24 06:25:24
本文介绍了如何等待所有异步调用完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我将Mongoose与Node.js结合使用,并具有以下代码,这些代码将在所有save()调用完成后调用回调.但是,我认为这是一种非常肮脏的方式,并且希望了解完成此操作的正确方法.

I'm using Mongoose with Node.js and have the following code that will call the callback after all the save() calls has finished. However, I feel that this is a very dirty way of doing it and would like to see the proper way to get this done.

function setup(callback) { // Clear the DB and load fixtures Account.remove({}, addFixtureData); function addFixtureData() { // Load the fixtures fs.readFile('./fixtures/account.json', 'utf8', function(err, data) { if (err) { throw err; } var jsonData = JSON.parse(data); var count = 0; jsonData.forEach(function(json) { count++; var account = new Account(json); account.save(function(err) { if (err) { throw err; } if (--count == 0 && callback) callback(); }); }); }); } }

推荐答案

您可以使用异步或步骤.

此外,我已经编写了一个小模块,可以为您处理装载夹具,因此您只需执行以下操作:

Also, I've written a small module that handles loading fixtures for you, so you just do:

var fixtures = require('./mongoose-fixtures'); fixtures.load('./fixtures/account.json', function(err) { //Fixtures loaded, you're ready to go };

Github: github/powmedia/mongoose-fixtures

它还将加载灯具文件或对象的目录.

It will also load a directory of fixture files, or objects.

更多推荐

如何等待所有异步调用完成

本文发布于:2023-11-28 06:46:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641351.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!