Reputation: 568
I have app on Node.js, consisting of two files. First file contains function with construction if(..) { ... } else { ... }
, second file contains functions whose result in an argument in if()
and contains request to database. Example:
var args = require('./File_2');
if(args.test() && args.example()) {
//action
}
else {
//action
}
function test() {
mysql.query('SELECT * FROM `table` WHERE `name` = "test"', function(err, rows) {
if(rows.length == 0) {
return false;
}
else {
return true;
}
}
}
function example() {
mysql.query('SELECT * FROM `table` WHERE `name` = "example"', function(err, rows) {
if(rows.length == 0) {
return false;
}
else {
return true;
}
}
}
exports.test = test;
exports.example = example;
The request comes after some time, so in if()
arguments equal undefined, undefined
. How to make if/else
construction wait request result? I have two ideas - promises and module async
. I think async
- the wrong decision. How to use promises in this situation? Which solution is preferable? I will be glad to any answers.
(Sorry for bad english.)
Upvotes: 1
Views: 269
Reputation: 1450
async is a pretty awesome library, but in node you will use a callback (not a return). Here is an example:
var async = require('async')
function test(callback){
//simulate one async method call
setTimeout(function(){
callback(null, "test_finished")
},100)
}
function example(callback){
//simulate another async method call
setTimeout(function(){
callback(null, "example finished")
},500)
}
function compare(err, results){
//results will maintain order of array in parallel
console.log(results[0], results[1]);
}
async.parallel([
example,
test
], compare);
Upvotes: 3