在Node.js中可以使用Promise来实现保留临时数据直到发送响应的功能。下面是一个示例代码:
const http = require('http');
function requestData() {
return new Promise((resolve, reject) => {
// 模拟异步请求数据
setTimeout(() => {
const data = 'This is the temporary data';
resolve(data);
}, 2000);
});
}
http.createServer((req, res) => {
requestData()
.then(data => {
// 在Promise resolve后发送响应
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(data);
res.end();
})
.catch(err => {
res.writeHead(500, {'Content-Type': 'text/plain'});
res.write('Error occurred');
res.end();
});
}).listen(3000);
console.log('Server running at http://localhost:3000/');
在上面的示例中,requestData
函数返回一个Promise对象,用于模拟异步请求数据。在创建HTTP服务器的回调函数中,我们通过调用requestData
函数来获取数据,并在Promise resolve后发送响应。
运行上述代码后,服务器会在http://localhost:3000/上监听请求。当有请求到达时,服务器会等待2秒后发送响应,并将临时数据发送给客户端。
上一篇:保留零值的添加计数器
下一篇:保留路径并显示文件名