当我想查询数据时,我得到了这个mongodb代码,但是保存数据异步功能正在进行,并显示我保存的数据而不保存来自findOne函数的响应。如何停止该功能,直到我得到响应。
代码如下:
var mongoose = require("mongoose");
mongoose.connect('mongodb://0.0.0.0:27017/FI1');
var Schema = mongoose.Schema;
var userData = mongoose.model('transactionData',new Schema({}),'transactionData');
var dataFromQuery;
userData.find({transactionId:'4087052'}).then(function(doc){ console.log("data i am getting in async function =>",doc); dataFromQuery=doc; });
console.log(" <= this variable in which i want to save query data. that is undefined rightnow!",dataFromQuery);
输出如下:
node databasemodules.js
<= this variable in which i want to save
query data. that is undefined rightnow ! undefined data i am getting
in async function => [ { _id: 5b16ad7ca37a312b60d87bd6,
transactionId: '4087052',
Accountid: '2345',
bertono: 2 } ]
我在findOne回调函数中的console.log中获取输出,但我无法将其保存在dataFromQuery变量中。
为async await添加了新代码:
var mongoose = require("mongoose");
mongoose.connect('mongodb://0.0.0.0:27017/FI1');
var Schema = mongoose.Schema;
//var userData = mongoose.model('transactionData',new Schema({ _id: String, transactionId: String,beneficiary: String,amount: String,signature: String,Bankid: String,Receiversname: String,Accountid: String, beneficiaryFees: Number }),'transactionData');
var userData = mongoose.model('transactionData',new Schema({}),'transactionData');
(async () => {
let result = await dbQuery(); // waiting for resolve or reject
// you can use the query result now
})();
function dbQuery() {
return new Promise(function(resolve, reject) { // create the promise
userData.find({transactionId:'4087052'}).then(function(error, doc) {
if (error) { reject(error); }
else { resolve(doc);} // resolve the promise
console.log(">>>",doc)
})
})
};
得到这个错误:
undefined (node:8612) UnhandledPromiseRejectionWarning: [object Array] (node:8612) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not han dled with .catch(). (rejection id: 1) (node:8612) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. –
发布于 2018-08-03 09:54:08
Node.js是异步的,它不会等待数据库查询完成,那是最后一个console.log
。
查询完成后使用:
userData.find({transactionId:'4087052'}).then(function(doc) {
console.log("data i am getting in async function =>",doc);
dataFromQuery=doc;
// Do what you want with the dataFromQuery here
});
另一个需要考虑的选择是ES8 Async / Await方式,例如:
脚本在继续执行之前等待解析promise。
let result = await dbQuery(); // waiting for resolve or reject
// you can use the query result now
function dbQuery() {
return new Promise(function(resolve, reject) { // create the promise
userData.find({transactionId:'4087052'}).then(function(error, doc) {
if (error) { reject(error); }
else { resolve(doc); } // resolve the promise
})
})
};
https://stackoverflow.com/questions/-100001885
复制相似问题