[英]how to make async requests from client to server?
想要从客户端到服务器发出一些异步请求。
我使用 http 模块设置本地服务器,并将此功能导出到主应用程序文件。 在客户端文件中,我编写了发出 http 请求的函数,并多次调用此函数。
//server
const http = require('http');
const ms = 2000;
const init = () => {
http.createServer((req,res) => {
sleep(ms);
console.log(req.method);
console.log("After sleeping 2 seconds,hello from server");
res.end();
}).listen(5000, () => {
console.log("server running");
});
}
function sleep(ms) {
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms);
console.log("Sleep 2 seconds.");
}
module.exports.init = init;
//client
const url = "http://127.0.0.1:5000";
const http = require('http');
const getData = async url => {
await http.get(url, res => {
res.on('data', chunk => {
console.log("chunk : "+chunk);
});
res.on('end', () => {
console.log("response ended.");
});
}).on("error", (error) => {
console.log("Error: " + error.message);
});
};
const makeRequests = () => {
for (let i = 0; i < 3; i++) {
getData(url);
}
}
module.exports.makeRequests = makeRequests;
//app
const server1 = require('./server1');
const client = require('./client');
server1.init();
client.makeRequests();
我如何正确使用异步等待? 为什么它现在打印“块”?
想要从客户端到服务器发出一些异步请求。
好吧,您的代码实际上是异步的。
我如何正确使用异步等待?
如何正确使用 async/await 。 有示例如何使用。
为什么它现在打印“块”?
http.get(url, res => {
res.on('data', chunk => {
console.log("chunk : "+chunk);
});
res.on('end', () => {
console.log("response ended.");
});
http.get(url, callback) ... response.on("data") 如果收到一个新的块就会被触发。 因此它会一直读取,直到响应流获得 EOF(文件结尾)。 如果您想一次保存和读取整个数据,您可以通过追加将块写入变量并在“结束”时读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.