Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

BestBuy API won't query in a loop

I am very new to Javascript and I am trying to utilize BestBuy’s api to grab data on a specific sku number every 3 seconds.

The call to the api works as expected on its own but when I move the call inside a while loop, I do not get anything and the console.log in the function is not hit.

Not sure where to go from here and I am starting wonder if this api call can only be called by itself.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Would appreciate any help.

var bby = require('bestbuy')('<Actual BestBuy Api key in original code>');

var isSoldOut = true;

while(isSoldOut)
{
  console.log("HERE");
  bby.products(6465789,{show:'sku,name,salePrice,onlineAvailability,inStorePickup,onlineAvailabilityUpdateDate'}).then(function(data){
    console.log(data);

    if (data['onlineAvailability'] == false)
    {
    isSoldOut = false;
    console.log(isSoldOut);
    }
  });
  
  wait(3000);
}

function wait(ms)
{
    var d = new Date();
    var d2 = null;
    do { d2 = new Date(); }
    while(d2-d < ms);
}

>Solution :

Your while loops are constantly blocking the thread, so your callback function can’t run.

Instead of the while loops, you can use an interval:

var bby = require('bestbuy')('<Actual BestBuy Api key in original code>');

function check() {
  console.log("HERE");
  bby.products(6465789,{show:'sku,name,salePrice,onlineAvailability,inStorePickup,onlineAvailabilityUpdateDate'}).then(function(data){
    console.log(data);

    if (data['onlineAvailability'] == false)
    {
      clearInterval(loop);
      console.log("In Stock");
    }
  });
}

const loop = setInterval(check, 3000);

Even cleaner may be using async/await to wait 3 seconds after receiving each response:

var bby = require('bestbuy')('<Actual BestBuy Api key in original code>');

const wait = require('util').promisify(setTimeout);

async function check() {
  console.log("HERE");

  const data = await bby.products(6465789,{show:'sku,name,salePrice,onlineAvailability,inStorePickup,onlineAvailabilityUpdateDate'});
  console.log(data);

  if (data['onlineAvailability'] == false)
  {
    console.log("In Stock");
    return;
  }

  await wait(3000);
}

check();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading