我試圖用一個回調來指示所有async
工人是完全異步回調的錯誤,但我得到了可怕的的Node.js上queue.drain
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();
}
任何援助將不勝感激!
編輯,添加了一些僞代碼來演示如何refreshData正在使用:
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)
}
}
你怎麼調用'refreshData' - 顯然沒有第二個參數是一個函數 –
謝謝,yes refreshData是一個函數,在完成一個單獨的GET請求時被調用。 – leo
編輯帖子添加僞代碼去展示 – leo