我试图使用回调来指示所有async
工作人员何时完成,但我遇到了可怕的
TypeError: callback is not a function.
我想单独处理数据中的每个元素,并在完成后让 queue.drain
发送 callback(data)
以在完成时刷新数据。我已经准备好了async documentation ,但显然我没有得到任何东西。
function refreshData(postData, callback) {
var options = {
host: 'www.myhost.com',
port: 443,
path: '/pulldata,
method: 'POST',
headers: {
"Content-Type": "application/json"
}
};
var req = https.request(options, function(res) {
var headers = res.headers
var d = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
d = d + chunk;
});
res.on('end', function() {
if (res.statusCode == '200') {
data = JSON.parse(d);
queue = async.queue(function (task, cb) {
processData(task,cb);
},1);
//this is were the errors are
queue.drain = function() {
callback(data)
};
for(i=0; i<data.length; i++) {
queue.push(data[i],'');
}
} else {
callback(false)
}
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postData);
req.end();
}
任何帮助将不胜感激!
编辑,添加一些伪代码来演示如何使用刷新数据:
Node https.createServer(req,res) {
req.on(){
read userData
}
req.end(){
validateUser(userData, function(callbackData) {
if(callbackData==false) {
//bad user or error with request
res.writeHead(404);
res.end('bye');
} else {
//good user and responses
res.writeHead(200);
res.end(callbackData);
}
})
}
}
function validateUser(userData,callback) {
//do some stuff to validate
if(userData is good) {
//call refreshData if user
refreshData(userData,callback)
} else {
callback(false)
}
}
最佳答案
[编辑]添加了回调 正如您指向的文档中给出的,更改此行
queue.push(data[i],'');
到
queue.push(data[i], function(err){
// handle error
});
在这里试试 async-queue-callback
关于javascript - queue.drain 上的 node.js 异步回调错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43336436/