在承诺之间发送参数



我正在用node.js做一个异步进程。使用的承诺。我的代码是这样的:

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);

所有在我的代码工作得很好,但现在,我想连接在secondFunction我的字符串从firstFunction收到其他字符串,例如"MyNewString"。有人知道怎么解吗?我可以从我的firstFunction发送"MyNewString"到我的secondFunction吗?提前谢谢。

问好。

最好的解决方法是resolve promise with object。而不是只返回一个值-查询DB的结果,你可以返回包含所需值的对象。

与绑定

:

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);

关闭

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);

带有匿名函数表达式

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);

最新更新