简体   繁体   中英

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. at the client file i write function that makes http request and i call this function number of times.

//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 . 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. So it will read until the response stream gets an EOF ( End Of File ). If you wanna save & read the whole data at once you can write your chunks into a variable by append and read at "end".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM