如何解决这个MongoDB / Node异步问题? [英] How to get around this MongoDB/Node asynchronous issue?

查看:100
本文介绍了如何解决这个MongoDB / Node异步问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

// Retrieve
var MongoClient = require("mongodb").MongoClient;
var accounts = null;
var characters = null;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/bq", function(err, db) {
   if(err) { return console.dir(err); }

    db.createCollection('accounts', function(err, collection) {
        if(err) { return console.dir(err); }
        else { accounts = collection; }

        createAccount("bob","bob");
        createAccount("bob","bob");
        createAccount("bob","bob");
        createAccount("bob","bob");
    });
});


function createAccount(email, password)
{
    accounts.findOne({"email":email}, function(err, item) {
        if(err) { console.dir(err); }
        else {
            if(item === null) {
                accounts.insert({"email":email, "password":password}, function(err, result) {
                    if(err) { console.dir(err); }
                    else { console.dir("Account " + email + " created."); }
                });
            }
            else {
                console.dir("Account already exists.")
            }

        }
    });
}

当我第一次运行脚本时,我最终得到4个帐户鲍勃。当我第二次运行它时,我收到4条消息,该帐户已经存在。

When I run the script the first time, I end up with 4 accounts for bob. When I run it the second time, I get 4 messages that the account already exists.

我很确定我知道为什么会这样,我已经来了解决方案最好是使用某种队列来一次一个地处理数据库的每次读/写。我想知道的是,这是否是正确的方法,以及通常的最佳做法是什么?

I'm pretty sure I know why this is, and the solution I have come up with is to use some kind queue for processing each read/write of the database in order one at a time. What I am wanting to know, is whether that is the proper way to go about it, and what would the general best practice for this be?

推荐答案

有些语言提供了一种特殊的语言结构来处理这个问题。例如,C#具有 async / 等待关键字,可让您像调用同步API一样编写代码。

Some languages provide a special language construct to deal with this problem. For example, C# has async/await keywords that let you write the code as if you were calling synchronous APIs.

JavaScript没有,您必须使用回调链接 createAccount 调用。

JavaScript does not and you have to chain the createAccount calls with callbacks.

有些人开发了可以帮助您组织此代码的库。例如, async 步骤节点承诺

Some people have developed libraries that may help you organize this code. For example async, step, node-promise and Q

您还可以使用光纤库,一个本机库,使用fiber / coroutines扩展JavaScript运行时。

You can also use the fibers library, a native library that extends the JavaScript runtime with fibers / coroutines.

有些人使用类似于 async的构造扩展了语言 / 等待 streamline.js IcedCoffeeScript wind.js 。例如,streamline.js(我是作者,所以我显然有偏见)使用 _ 作为一个特殊的回调占位符,让你把你的例子写成:

And some people have extended the language with constructs that are similar to async/await: streamline.js, IcedCoffeeScript or wind.js. For example, streamline.js (I'm the author so I'm obviously biased) uses _ as a special callback placeholder and lets you write your example as:

var db = MongoClient.connect("mongodb://localhost:27017/bq", _):
var accounts = db.createCollection('accounts', _);
createAccount("bob","bob", _);
createAccount("bob","bob", _);
createAccount("bob","bob", _);
createAccount("bob","bob", _);

function createAccount(email, password, _) {
    var item = accounts.findOne({"email":email}, _);
    if (item === null) {
        accounts.insert({"email":email, "password":password}, _);
        console.log("Account " + email + " created."); }
    } else {
        console.log("Account already exists.")
    }
}

最后但并非最不重要的是,新的语言功能,如正在讨论生成器延迟函数的未来版本的JavaScript(生成器非常可能落在ES6中,延期函数似乎有点停滞。)

And, last but not least, new language features such as generators and deferred functions are being discussed for future versions of JavaScript (generators are very likely to land in ES6, deferred functions seem to be a bit stalled).

所以你有很多选择:


  • 坚持回调

  • 使用帮助库

  • 使用光纤运行时扩展

  • 使用语言扩展

  • 等待ES6

  • stick to callbacks
  • use a helper library
  • use the fibers runtime extension
  • use a language extension
  • wait for ES6

这篇关于如何解决这个MongoDB / Node异步问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆