本文介绍了最简单的方法等待一段异步任务完成后,在Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要下降一些MongoDB的集合,但是这是一个异步任务。在code将是:

I want to drop some mongodb collections, but that's an asynchronous task. The code will be:

var mongoose = require('mongoose');

mongoose.connect('mongo://localhost/xxx');

var conn = mongoose.connection;

['aaa','bbb','ccc'].forEach(function(name){
    conn.collection(name).drop(function(err) {
        console.log('dropped');
    });
});
console.log('all dropped');

控制台显示:

all dropped
dropped
dropped
dropped

什么是确保最简单的方法都下降了将要打印的所有集合后已被删除?任何第三方可以用来简化code。

What is the simplest way to make sure all dropped will be printed after all collections has been dropped? Any 3rd-party can be used to simplify the code.

推荐答案

我看你使用猫鼬所以你是在谈论服务器端JavaScript。在这种情况下,我建议在看,并使用 async.parallel(...)。你会发现这个模块真正有用的 - 它的开发是为了解决你在挣扎的问题。您code可能看起来像这样

I see you are using mongoose so you are talking about server-side JavaScript. In that case I advice looking at async module and use async.parallel(...). You will find this module really helpful - it was developed to solve the problem you are struggling with. Your code may look like this

var async = require('async');

var calls = [];

['aaa','bbb','ccc'].forEach(function(name){
    calls.push(function(callback) {
        conn.collection(name).drop(function(err) {
            if (err)
                return callback(err);
            console.log('dropped');
            callback(null, name);
        });
    }
)});

async.parallel(calls, function(err, result) {
    /* this code will run after all calls finished the job or
       when any of the calls passes an error */
    if (err)
        return console.log(err);
    console.log(result);
});

这篇关于最简单的方法等待一段异步任务完成后,在Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 11:07