Rodrigo Dias Rodrigo Dias - 6 days ago 5
Javascript Question

Can I use $.each() with $.ajax() to consult a api?

I have an array with 2 values, for each value I need to make a query via AJAX to an API to query the stock. If there is stock for all three I execute a message, if there is no stock of any of these I execute another. For every

data-sku
I need to do the check.

Can I use
$.each()
with
$.ajax()
inside it to do it? Or is there a better way?
https://jsfiddle.net/o2e97w2s/

<div class="SKU-e-qtd">
<div data-sku="421">4</div>
<div data-sku="4008">1</div>
</div>


var listSkuIds = $(".SKU-e-qtd div").map(function() {
return $(this).attr("data-sku");
}).get();

$.ajax({
url: "https://webapi.xxxxx.com.br/api/estoque/ProdutoProntaEntregapProductId?productid=" + listSkuIds,
dataType: 'json'
}).done(function(data) {
if (data >= '1' && data !== 'E') {
console.log('// Do Anything');
} else {
console.log('// Do Nothing');
};
});

Answer

The best way to achieve this would be to send all the SKU values to the API in a single request and have it return back the data of all SKUs in a single JSON.

If you don't have control of the API, then you can achieve what you need by looping through the SKUs and creating an array of the Deferred objects returned from $.ajax(). When each request completes you can mark the stock state in a separate array.

You can then apply() the array of Deferreds to $.when so that you can execute some logic after all the requests have completed to check the stock levels for all items. Something like this:

var stock = [];
var requests = $(".SKU-e-qtd div").map(function() {
  var sku = $(this).data('sku');
  return $.ajax({
    url: "https://webapi.toqueacampainha.com.br/api/estoque/ProdutoProntaEntregapProductId?productid=" + sku,
    dataType: 'json'
  }).done(function(data) {
    stock.push(data >= '1' && data !== 'E');
  });
}).get();

console.log('awaiting AJAX...')

$.when.apply($, requests).done(function() {
  if (stock.indexOf(false) != -1) {
    console.log('some stock missing');
  } else {
    console.log('all in stock!');
  }
  
  console.log(stock);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="SKU-e-qtd">
    <div data-sku="421">4</div>
    <div data-sku="4008">1</div>
</div>

Comments