JC1
JC1

Reputation: 879

Polling URL synchronously

I'm looking to make a function which polls a certain URL synchronously (i.e. send one request, wait for it to come back before sending another). However, I'm unsure of why this is not working.

const request = require('request')

let count = 0;

function test() {
    setInterval(() => {
        console.log(count)
        request({uri: "https://google.com"}, (err, resp, body) => {
            console.log(count)
            count++;
        })
      }, 100);
}

I would wait it to print count in sequential order (1 2 3 4 5 ...) but it currently prints same numbers several times indicating that it's not the behaviour that I intended.

How do I get it to wait for the callback before doing another interval?

Upvotes: 1

Views: 1154

Answers (2)

Hồng Lưu
Hồng Lưu

Reputation: 29

setInterval is not suitable for promises because it triggers a callback multiple times, while promise resolves once.

You can try this

var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

test = async ()=> {
  while (true) {
    await request({ uri: "https://google.com" }, (err, resp, body) => {
        count++;   
    })
    await wait(1000);
    if(count == 100)
        break;
    console.log(count)
 }
}
test();

Upvotes: 0

Ace
Ace

Reputation: 1146

What you are doing is sending the request every 100 milliseconds, nothing in your code waits for a response. To do this, you want to remove the setInterval and just call the function again in the callback.

const request = require('request')

let count = 0;

function test() {
    console.log(count)
    request({uri: "https://google.com"}, (err, resp, body) => {
        console.log(count)
        count++;
        test();
    })
}

Upvotes: 2

Related Questions