我有一个代码来做一些计算。 如何以asyn方式编写此代码? 查询数据库时,似乎无法同步获得结果。 那么如何实现这种功能呢?
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;
}
答案 0 :(得分:3)
它不可能返回异步函数的结果,它只会返回自己的函数范围。
这也是不可能的,结果将始终保持不变(null)
client.query(someSql, function (err, rows) {
result = rows[0].value;
});
return result;
将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中放置一个回调参数,并像以前一样调用该函数。
我建议你查看async这是一个很棒的图书馆,无需处理这种麻烦
答案 1 :(得分:0)
这是一种通过使用事件实现循环来执行计算(模拟异步数据库调用)的非常粗略的方法。
正如Brmm所提到的,一旦你去异步,你必须一直异步。下面的代码只是一个示例,让您了解理论过程应该是什么样子。有几个库使得处理asynch调用的同步过程更加清晰,你也想要查看:
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);