[英]how to make async requests from client to server?
want to make few async requests from client to server.想要从客户端到服务器发出一些异步请求。
i setting up local server with http module , and export this function to main app file.我使用 http 模块设置本地服务器,并将此功能导出到主应用程序文件。 at the client file i write function that makes http request and i call this function number of times.在客户端文件中,我编写了发出 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();
how do i use the async await proprely ?我如何正确使用异步等待? and why its now printing the "chunk" ?为什么它现在打印“块”?
want to make few async requests from client to server.想要从客户端到服务器发出一些异步请求。
Well, your code is actually async.好吧,您的代码实际上是异步的。
how do i use the async await proprely ?我如何正确使用异步等待?
How to use async/await correctly . 如何正确使用 async/await 。 There are examples how to use.有示例如何使用。
and why its now printing the "chunk" ?为什么它现在打印“块”?
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") gets fired if a new chunk is received. http.get(url, callback) ... response.on("data") 如果收到一个新的块就会被触发。 So it will read until the response stream gets an EOF ( End Of File ).因此它会一直读取,直到响应流获得 EOF(文件结尾)。 If you wanna save & read the whole data at once you can write your chunks into a variable by append and read at "end".如果您想一次保存和读取整个数据,您可以通过追加将块写入变量并在“结束”时读取。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.