使用promise将asynchronous函数的结果作为“variables”返回

我在NodeJS中asynchronous执行时遇到了问题。 特别是,我有很多用例,我希望在代码中稍后使用asynchronous请求的结果,而不想将整个事件包装在另一个缩进级别,如async.parallel

我知道解决这个问题的方法是使用承诺,但我正在努力实现正确的实施,而我尝试的资源并没有帮助。

我目前的问题是这样的:我需要立即得到一个MongoDB文档_id插入时。 我已经从使用MongoJS切换到使用官方的MongoDB驱动程序,因为我知道MongoJS不支持承诺。 任何人都可以通过提供一个基本的例子来说明如何使用promise来返回这个值吗?

再次感谢。

使用node.js驱动程序,使用返回promise的集合的insert()方法。 以下示例演示了这一点:

 var Db = require('mongodb').Db, MongoClient = require('mongodb').MongoClient, Server = require('mongodb').Server; var db = new Db('test', new Server('localhost', 27017)); // Fetch a collection to insert document into db.open(function(err, db) { var collection = db.collection("post"); // Create a function to return a promise function getPostPromise(post){ return collection.insert(post); } // Create post to insert var post = { "title": "This is a test" }, promise = getPostPromise(post); // Get the promise by calling the function // Use the promise to log the _id promise.then(function(posts){ console.log("Post added with _id " + posts[0]._id); }).error(function(error){ console.log(error); }).finally(function() { db.close(); }); }); 

你也可以使用Mongoose的save()方法,因为它返回一个Promise 。 下面是一个基本的例子:

 // test.js var mongoose = require('mongoose'), Schema = mongoose.Schema; // Establish a connection mongoose.connect('mongodb://localhost/test', function(err) { if (err) { console.log(err) } }); var postSchema = new Schema({ "title": String }); mongoose.model('Post', postSchema); var Post = mongoose.model('Post'); function getPostPromise(postTitle){ var p = new Post(); p.title = postTitle; return p.save(); } var promise = getPostPromise("This is a test"); promise.then(function(post){ console.log("Post added with _id " + post._id); }).error(function(error){ console.log(error); }); 

运行应用程序

 $ node test.js Post added with _id 5696db8a049c1bb2ecaaa10f $ 

那么你可以使用Promise.then()的传统方法,或者如果你可以使用ES6,可以尝试生成器函数(生成器直接包含在Node中,不需要运行时标志)。 这样,你可以简单地写这个代码:

 //You can use yield only in generator functions function*() { const newDocument = new Document({firstArg, SecondArg}); const savedDocument = yield newDocument.save(); //savedDocument contains the response from MongoDB 

}

你可以在这里阅读更多关于函数*