javascript - NodeJS : async module: passing arguments

标签 javascript node.js callback asynccallback node-async

我正在尝试使用回调将参数传递到 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 函数需要 request 变量。回调函数需要响应变量。知道如何实现吗?我尝试将请求和响应放入对象数组中,但该数组未正确传递到 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(); 
}

关于javascript - NodeJS : async module: passing arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35782628/

相关文章:

python - 从回调中查找父函数的参数

javascript - 在 JavaScript 中提取从 Servlet 返回的 JSON

node.js - 如何在 Node 中启用 Intl 以使用 Jest 进行测试?

html - EJS 渲染 HTML

css - jQuery - 无法在 ajax 回调函数中设置 css 属性

javascript - 传递回调的正确方法是什么?

javascript - jQuery 事件未触发。

随着时间的流逝,javascript 计时器计数非常快

javascript - 无法在 JavaScript 幻灯片中嵌入标签

javascript - 为什么控制流不遵循代码执行顺序?