Tecnico Tecnico - 25 days ago 11
Node.js Question

Send parameters between promises

Im doing a asynchronous process with node.js. using promises. My code is like this:

var net = require('net');
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('MyBBDD.db');
var net = require('net');
var Q = require("q");

var firstFunction = function(v_user, v_mystring){
var deferred = Q.defer();
var mi;
stmt = db.prepare("SELECT text1 FROM my_table WHERE user = ?");
stmt.bind (v_user);
stmt.get(function(error,row){
if(!error && row){
deferred.resolve({string: v_mystring, query: row.text1});
}
deferred.reject(new Error(error));
});
return deferred.promise;
};

var secondFunction = function(result){
console.log(result.string);
console.log(result.query);
};

firstFunction('user000','Hello').then(secondFunction);


All in my code work fine but now, I want to concatenate in secondFunction my string received from firstFunction with other string for example "MyNewString".
Somebody know how can I solve it? Can I send "MyNewString" from my firstFunction to my secondFunction?
Thanks in advance.

Best regards.

Answer

The best to solve it will be resolve promise with object. Instead of returning just one value - result of querying DB you can return object that covers needed value.

With bind:

function firstFunction(string) {
  return Promise.resolve({string: string, query: 'some result of query'})
}

function secondFunction(otherText, result) {
  console.log(result.query) // you have still access to result of query
  return result.string + otherText
};

firstFunction('foo').then(secondFunction.bind(null, 'bar')).then(console.log);

With closure

function firstFunction(string) {
  return Promise.resolve({string: string, query: 'some result of query'})
}

function secondFunction(text) {
  return function(result) {
    return result.string + text
  }
};

firstFunction('foo').then(secondFunction('bar')).then(console.log);

With anonymous function expression

function firstFunction(string) {
  return Promise.resolve({string: string, query: 'some result'})
}

function secondFunction(text, otherText) {
  return text.string + otherText
};

firstFunction('foo').then(function(result) {
  return secondFunction(result, 'bar')
}).then(console.log);

Comments