Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何在nodejs中实现此asyn功能_Mysql_Node.js_Asynchronous - Fatal编程技术网

Mysql 如何在nodejs中实现此asyn功能

Mysql 如何在nodejs中实现此asyn功能,mysql,node.js,asynchronous,Mysql,Node.js,Asynchronous,我有一个代码来做一些计算。 如何以一种简单的方式编写此代码? 在查询数据库时,似乎无法同步得到结果。 那么如何实现这种特性呢 function main () { var v = 0, k; for (k in obj) v += calc(obj[k].formula) return v; } function calc (formula) { var result = 0; if (formula.type === 'SQL') {

我有一个代码来做一些计算。 如何以一种简单的方式编写此代码? 在查询数据库时,似乎无法同步得到结果。 那么如何实现这种特性呢

function main () {
    var v = 0, k;
    for (k in obj) 
        v += calc(obj[k].formula)
    return v;
}

function calc (formula) {
    var result = 0;
    if (formula.type === 'SQL') {
        var someSql = "select value from x = y"; // this SQL related to the formula;
        client.query(someSql, function (err, rows) {
            console.log(rows[0].value);
            // *How can I get the value here?*
        });
        result = ? // *How can I return this value to the main function?*
    }
    else 
        result = formulaCalc(formula); // some other asyn code
    return result;
}

不可能返回异步函数的结果,它只会在自己的函数范围内返回

这也是不可能的,结果将始终保持不变(null)

在calc()函数中放置一个回调函数作为第二个参数,并在client.query回调函数中调用该函数并返回结果

function main() {
   calc(formula,function(rows) {
      console.log(rows) // this is the result
   });
}

function calc(formula,callback) {
   client.query(query,function(err,rows) {
       callback(rows);
   });
}
现在,如果希望main返回该结果,还必须在main中放置一个回调参数,并像前面一样调用该函数


我建议您查看一下它是一个很好的库,不必处理这种麻烦

这里有一种非常粗糙的方法,通过使用事件实现循环来执行计算(模拟异步数据库调用)

正如Brmm所提到的,一旦你开始异步,你就必须一路异步。下面的代码只是一个示例,让您了解理论上的流程应该是什么样子。有几个库可以使异步调用的同步过程处理更为干净,您也需要研究这些库:

var events = require('events');
var eventEmitter = new events.EventEmitter();
var total = 0;
var count = 0;
var keys = [];

// Loop through the items
calculatePrice = function(keys) {
    for (var i = 0; i < keys.length; i++) {
        key = keys[i];
        eventEmitter.emit('getPriceFromDb', {key: key, count: keys.length});
    };
}

// Get the price for a single item (from a DB or whatever)
getPriceFromDb = function(data) {
    console.log('fetching price for item: ' + data.key);
    // mimic an async db call
    setTimeout( function() {
        price = data.key * 10;
        eventEmitter.emit('aggregatePrice', {key: data.key, price: price, count: data.count});
    }, 500);
}

// Agregate the price and figures out if we are done
aggregatePrice = function(data) {

    count++;
    total += data.price;
    console.log('price $' + price + ' total so far $' + total);

    var areWeDone = (count == data.count);
    if (areWeDone) {
        eventEmitter.emit('done', {key: data.key, total: total});   
    } 
}

// We are done.
displayTotal = function(data) {
    console.log('total $ ' + data.total);
}

// Wire up the events
eventEmitter.on('getPriceFromDb', getPriceFromDb);
eventEmitter.on('aggregatePrice', aggregatePrice);
eventEmitter.on('done', displayTotal);

// Kick of the calculate process over an array of keys
keys = [1, 2, 3]
calculatePrice(keys);
var events=require('events');
var eventEmitter=new events.eventEmitter();
var合计=0;
var计数=0;
var键=[];
//循环浏览项目
calculatePrice=功能(键){
对于(变量i=0;i
var events = require('events');
var eventEmitter = new events.EventEmitter();
var total = 0;
var count = 0;
var keys = [];

// Loop through the items
calculatePrice = function(keys) {
    for (var i = 0; i < keys.length; i++) {
        key = keys[i];
        eventEmitter.emit('getPriceFromDb', {key: key, count: keys.length});
    };
}

// Get the price for a single item (from a DB or whatever)
getPriceFromDb = function(data) {
    console.log('fetching price for item: ' + data.key);
    // mimic an async db call
    setTimeout( function() {
        price = data.key * 10;
        eventEmitter.emit('aggregatePrice', {key: data.key, price: price, count: data.count});
    }, 500);
}

// Agregate the price and figures out if we are done
aggregatePrice = function(data) {

    count++;
    total += data.price;
    console.log('price $' + price + ' total so far $' + total);

    var areWeDone = (count == data.count);
    if (areWeDone) {
        eventEmitter.emit('done', {key: data.key, total: total});   
    } 
}

// We are done.
displayTotal = function(data) {
    console.log('total $ ' + data.total);
}

// Wire up the events
eventEmitter.on('getPriceFromDb', getPriceFromDb);
eventEmitter.on('aggregatePrice', aggregatePrice);
eventEmitter.on('done', displayTotal);

// Kick of the calculate process over an array of keys
keys = [1, 2, 3]
calculatePrice(keys);