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.
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);
}
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();