S
S
SkyTaurus2015-09-06 18:24:50
Node.js
SkyTaurus, 2015-09-06 18:24:50

How to use defer.resolve and Q.all?

It is necessary to write a code that, depending on the condition, forms one or another sql query, and then executes it.
I tried several options, but it was not possible to get the desired result - the combination of dever.resolve and Q.all does not work as I need.
In this variant, node.js executes deferrer.resolve before Q.all, i.e. there is no data yet at the time of deferrer.resolve.

deferred = Q.defer()
if условие
   сформировать_sql_запрос
   deferred.resolve
else
   получить_дополнительные_данные
   Q.all(выполнить_sql_запросы_по_дополнительным_данным).then =>
      сформировать_sql_запрос
   deferred.resolve
deferred.promise.then =>
   выполнить_sql_запрос

In this variant, node.js executes deferrer.resolve after Q,all has completed, but before Q.all's .then.
deferred = Q.defer()
if условие
   сформировать_sql_запрос
   deferred.resolve
else
   получить_дополнительные_данные
   deferred.resolve Q.all(выполнить_sql_запросы_по_дополнительным_данным).then =>
      сформировать_sql_запрос
deferred.promise.then =>
   выполнить_sql_запрос

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Prozorov, 2015-09-07
@SkyTaurus

Here you can do without promises at all:

var async = require('async');
var mysqlConnection = ...;

function fetch (param, fetchCallback) { // fetchCallback (err, fetchedData)
    async.auto({

        queryOne: function (cb) {
            // если нет параметра для первого запроса идём дальше
            if (!param) return cb(null, null); 

            // сформировать_sql_запрос
            var queryStr = "QUERY TYPE ONE " + mysqlConnection.escape(param);
            cb(null, queryStr);
        },

        queryTwo: ['queryOne', function (cb, results) {
            // если первый запрос сформирован сразу идём дальше
            if (results.queryOne) return cb(null, null); 

            mysqlConnection.query("QUERY TO GET ADDITIONAL DATA", [...], function (err, data) {
                if (err) return cb(err);

                // сформировать_sql_запрос используя дополнительные данные из data
                var additionalParam = data[0]&& data[0].field || 'An default';
                var queryStr = "QUERY TYPE TWO BY ADDITIONAL DATA "  + mysqlConnection.escape(additionalParam);

                cb(null, queryStr);
            });
        }]

    }, function (err, results) {
        if (err) return fetchCallback(err);

        mysqlConnection.query(results.queryOne || results.queryTwo, [...], fetchCallback);
    });
}

When constructing queries using external parameters, don't forget to call mysqlConnection.escape(unsafe_param) on them to avoid SQL injections.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question