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

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

问题描述

我在使用 Node JS 进行同步调用时遇到问题.这是我的问题:

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

我有以下代码:

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
})

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

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