gpt4 book ai didi

javascript - 使用 Promises 响应来自 Node.js 的请求

转载 作者:行者123 更新时间:2023-12-02 17:31:31 25 4
gpt4 key购买 nike

我正在尝试设置 Node.js 脚本来使用 ECMAScript 6 Promise。我能够在 Node 脚本中完成我需要的工作,这需要多次获取外部服务器(因此暂时昂贵),但无法响应客户端,因为 Promises 构造会导致丢失对 Response 的引用(因此我猜)。

如何将 Response 对象传播到最后一个 Promise then() 并回复请求?

var http = require("http");
var Promise = require('es6-promise').Promise;
//...

var promise = new Promise(function(resolve, reject){
//...
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (data) {
buffer += data.toString();
});
res.on('end',function(d){
//...stuff done with buffer...
return resolve(0);
});
});

req.end();
});

promise.then(function(i){

//...expensive work on array...

return Promise.all(myArrayData);
});

promise.then(function(result){
//...want to reply to the request here, e.g.,...
res.write(result);
});

最佳答案

您只需将服务调用放入路由处理程序中即可:

app.get("/",function(req,res){
myService().then(function(result){
res.write(result);
// res.end();
});
});

就像在同步代码中一样,您在希望执行的上下文中调用函数:

var data = myService();
doSomethingWith(data);

关于javascript - 使用 Promises 响应来自 Node.js 的请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23022543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com