如何从 Node.js 快速操作处理程序执行延迟响应?
-
23-09-2019 - |
题
以下是一个最小的示例。 posix.cat
是一个返回 Promise 的函数, up
对结果做了一些事情,我想将其作为响应发送。
require.paths.unshift('lib');
require('express');
var posix = require('posix');
get('/', function () {
function up(s) {
return s.toUpperCase();
}
return posix.cat('/etc/motd').addCallback(up);
});
run(3001);
客户永远不会得到回应。
我也尝试过对此的变体:
get('/2', function () {
var myRequest = this;
function up(s) {
myRequest.respond(s.toUpperCase());
}
return posix.cat('/etc/motd').addCallback(up);
});
但这往往会使一切崩溃:
[object Object].emitSuccess (node.js:283:15)
[object Object].<anonymous> (node.js:695:21)
[object Object].emitSuccess (node.js:283:15)
node.js:552:29
node.js:1027:1
node.js:1031:1
解决方案
根据 这, ,方法 #2 的问题是 respond
在设置状态代码之前调用。
这有效:
get('/2', function () {
var myRequest = this;
function up(s) {
myRequest.halt(200, s.toUpperCase());
}
return posix.cat('/etc/motd').addCallback(up);
});
不隶属于 StackOverflow