节点JS同步数据库调用 [英] Node JS Synchronous database call

查看:290
本文介绍了节点JS同步数据库调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可能使同步调用时使用节点JS的一个问题。这里是我的问题:

我有以下的code:

  async.doWhilst(函数(回调){
    //一些code
    回电话();
},函数(){
    //进行数据库调用,并根据结果我应该
    //返回true,继续循环或假停在这里
},功能(错误){
   //做一些事情,当循环结束
})

问题是调用数据库时,它是异步调用和循环将继续返回正确的值。之前

感谢您了很多您的意见,我已经解决了移动问题的数据库调用循环code是这样的:

  VAR的结果= []
async.doWhilst(函数(回调){
    //一些code
    sequelize.query('某些查询)。成功(功能(结果){
        结果=结果;
        回电话();
    });
},函数(){
    //使用结果变量,它是从数据库中提取
    //返回true,继续循环或假停在这里
},功能(错误){
   //做一些事情,当循环结束
})


解决方案

我已经解决了由数据库调用移动到循环code这样的问题:

  VAR的结果= []
async.doWhilst(函数(回调){
    //一些code
    sequelize.query('某些查询)。成功(功能(结果){
        结果=结果;
        回电话();
    });
},函数(){
    //使用结果变量,它是从数据库中提取
    //返回true,继续循环或假停在这里
},功能(错误){
   //做一些事情,当循环结束
})

I have a problem using Node JS when making synchronous calls.. Here's my problem:

I have the following code:

async.doWhilst(function(callback) {
    //some code
    callback();
}, function() {
    //make a database call and based on the results I should 
    //return true to continue looping or false to stop here
}, function(err) {
   //do some things when the loop finishes
})

The problem is when calling the database it is asynchronous call and the loop continues before even returning the proper value.

Thank you alot for your comments, I have solved the problem by move the database call to the loop code like this:

var results = []
async.doWhilst(function(callback) {
    //some code
    sequelize.query('some query').success(function(result) {
        results = result;
        callback();
    });
}, function() {
    //use the results variable that is fetched from the database
    //return true to continue looping or false to stop here
}, function(err) {
   //do some things when the loop finishes
})

解决方案

I have solved the problem by move the database call to the loop code like this:

var results = []
async.doWhilst(function(callback) {
    //some code
    sequelize.query('some query').success(function(result) {
        results = result;
        callback();
    });
}, function() {
    //use the results variable that is fetched from the database
    //return true to continue looping or false to stop here
}, function(err) {
   //do some things when the loop finishes
})

这篇关于节点JS同步数据库调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆