【发布时间】:2016-08-16 12:50:39
【问题描述】:
我要实现的目标的简单概述:
- 对服务器上的特定 URL 进行 AJAX 调用
- Express Routes(在“app.js”中)然后在“Send.js”中运行 Node.js 代码
- “Send.js”的输出用作对“res.send”方法的 AJAX 请求的响应。
我的问题是“Send.js”使用了异步方法,所以我试图在“res.send(response)”中返回的“response”变量在发送响应时没有定义,因为“ “Send.js”中的“sendOn”函数自然会在异步代码完成之前完成。
我知道使用回调可能是这里的解决方案,因此在定义响应之前不会调用“res.send(response)”,鉴于我有两个单独的文件在这里:
app.js(简化版):
var send = require("./Files/Other/Send.js");
app.post('/Lamp-On', function (req, res)
{
var response = send.sendOn();
res.send(response);
});
Send.js(简体):
client.open 和 client.sendEvent 都是接受回调作为最终参数的异步方法,并且是外部 SDK 的一部分。
var sendMessage = function ()
{
var data = "on";
var message = new Message(data);
message.properties.add('Turn On');
console.log('Sending message to turn the lamp: ' + message.getData());
client.sendEvent(message, printResultFor('Message'));
};
var connectCallback = function () {
if (err) {
console.error('Could not connect: ' + err.message);
}
else {
console.log('Client connected');
client.on('message', function (msg) {
console.log('Id: ' + msg.messageId + ' Body: ' + msg.data);
client.complete(msg, printResultFor('completed'));
// reject and abandon follow the same pattern.
// /!\ reject and abandon are not available with MQTT
});
client.on('error', function (err) {
console.error(err.message);
});
client.on('disconnect', function () {
clearInterval(sendInterval);
client.removeAllListeners();
client.connect(connectCallback);
});
// Now call the sendMessage function.
sendMessage();
}
};
var sendOn = function () {
client.open(connectCallback);
return
};
// Helper function to print results in the console
function printResultFor(op) {
return function printResult(err, res) {
if (err !== null) {
console.log(op + ' error: ' + err.toString());
console.log(err);
}
if (res) {
console.log(op + ' status: ' + res.constructor.name);
};
};
}
exports.sendOn = sendOn;
我就是不知道怎么处理这么多异步回调!
最后说明:我既不要求也不期望任何人为我做这件事,但我希望你能指出正确的方向,提前谢谢。
【问题讨论】:
-
我的建议是使用Promise 来处理异步调用,您将能够执行类似
send.sendOn().then(function(response) {res.send(response);});的操作 -
我建议使用
async模块来避免这个问题https://github.com/caolan/async
标签: javascript ajax node.js asynchronous