Vladimir37
Vladimir37

Reputation: 568

Node.js - request to database and delay

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:

File_1 (part)

var args = require('./File_2');
if(args.test() && args.example()) {
    //action
}
else {
    //action
}

File_2 (part)

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

Answers (1)

Cody Gustafson
Cody Gustafson

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

Related Questions