首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在mongoose中调用同步功能?

如何在mongoose中调用同步功能?
EN

Stack Overflow用户
提问于 2018-08-03 00:02:18
回答 1查看 0关注 0票数 0

当我想查询数据时,我得到了这个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. –

EN

回答 1

Stack Overflow用户

发布于 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
    })
  })
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100001885

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档