使用 promise 将异步函数的结果作为“变量”返回
Using promises to return the result of an asynchronous function as a 'variable'
我在 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
}
您可以在此处阅读有关功能*的更多信息
相关文章:
- JS变量返回的对象不是值
- 存储区向变量返回了结果
- PHP/Ajax/jquery/JON-在Ajax Post之后将echo文本中的一部分作为变量返回
- PHP 函数不会向 JavaScript 变量返回值
- 当尝试使用ajax读取文件时,变量返回undefined
- Protractor-分配给element.all.locator.count的变量返回NaN why
- 范围变量返回长度错误
- 当chrome检查器为jQuery变量返回[object object]时,如何返回实际数据
- jQuery - img src 中的变量返回未定义
- 在angular.extend()中向变量返回一个承诺的值
- 循环遍历 HTML 内容并将值作为全局变量返回
- 为什么我的 JavaScript 提升的局部变量返回未定义,但提升的全局变量返回空白
- 解析 HTML 文件并将值作为 php 变量返回
- 提醒变量返回“未定义”
- 将一个函数中的局部变量返回给另一个函数
- PHP 将变量返回给外部 JavaScript
- 获取 JS 中的下拉变量返回未定义
- 使用 promise 将异步函数的结果作为“变量”返回
- 条件返回或单变量返回
- Meteor find使用变量返回null