NodeJS:异步模块:传递参数
NodeJS: async module: passing arguments
我正在尝试将参数传递给带有回调的 NodeJS 异步队列中的函数。我可以正确地传递一个参数,但它失败了两个。
提取(abc 由 HTTP POST 请求触发):
var queue = async.queue(doStuff, 5);
var abc = function(request, response)
{
queue.push(request, response, callback);
}
var doStuff = function(request, response, callback)
{
promiseChain...
then(function(result) {
//get stuff with result
callback(response, stuff);
}).close();
}
var callback = function(response, data)
{ response.writeHead(200, {'Content-Type':'text/plain'}); response.end(data); }
如果我从 doStuff 定义中删除响应(或请求)参数,那么我可以让它工作。使用两个参数 + 回调,它会抛出任何错误,指出第二个参数必须是回调函数。
doStuff 函数需要请求变量。回调函数需要响应变量。知道如何实施吗?我尝试将请求和响应放入一个对象数组,但该数组没有正确传递到 doStuff
。
If I remove the response (or request) argument from the doStuff definition, then I can make it work. With two arguments + the callback, it throws any error saying the 2nd argument must be a callback function.
async.queue().push()
只接受 2 个参数,push(task, [callback])
。这就是为什么您只会将第一个参数传递给您的工作人员。在将它们传递给 queue.push()
时,不要将参数展平,而是将它们作为对象传递给
queue.push({ req: request, res: response}, callback);
然后在doStuff
var doStuff = function(params, callback) {
// Get our params from the object passed through
var request = params.req;
var response = params.res;
promiseChain...
then(function(result) {
//get stuff with result
callback(response, stuff);
}).close();
}
我正在尝试将参数传递给带有回调的 NodeJS 异步队列中的函数。我可以正确地传递一个参数,但它失败了两个。
提取(abc 由 HTTP POST 请求触发):
var queue = async.queue(doStuff, 5);
var abc = function(request, response)
{
queue.push(request, response, callback);
}
var doStuff = function(request, response, callback)
{
promiseChain...
then(function(result) {
//get stuff with result
callback(response, stuff);
}).close();
}
var callback = function(response, data)
{ response.writeHead(200, {'Content-Type':'text/plain'}); response.end(data); }
如果我从 doStuff 定义中删除响应(或请求)参数,那么我可以让它工作。使用两个参数 + 回调,它会抛出任何错误,指出第二个参数必须是回调函数。
doStuff 函数需要请求变量。回调函数需要响应变量。知道如何实施吗?我尝试将请求和响应放入一个对象数组,但该数组没有正确传递到 doStuff
。
If I remove the response (or request) argument from the doStuff definition, then I can make it work. With two arguments + the callback, it throws any error saying the 2nd argument must be a callback function.
async.queue().push()
只接受 2 个参数,push(task, [callback])
。这就是为什么您只会将第一个参数传递给您的工作人员。在将它们传递给 queue.push()
时,不要将参数展平,而是将它们作为对象传递给
queue.push({ req: request, res: response}, callback);
然后在doStuff
var doStuff = function(params, callback) {
// Get our params from the object passed through
var request = params.req;
var response = params.res;
promiseChain...
then(function(result) {
//get stuff with result
callback(response, stuff);
}).close();
}