使用 promise 将异步函数的结果作为“变量”返回

Using promises to return the result of an asynchronous function as a 'variable'

本文关键字:变量 返回 结果 promise 异步 函数 使用      更新时间:2023-09-26

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

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

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

再次感谢。

使用

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

}

您可以在此处阅读有关功能*的更多信息