How to use promises in sequential

时间:2018-02-03 08:14:52

标签: javascript

I am new to programming. I need help to convert my codes into a sequential promise. It has checkboxes that fetched the checked values and then run the code displayed below. Appreciate any help.

var promises = [];
for (var i in checkValues) {
    //var request = AjaxAsync(checkValues[i]);
    //promises.push(request);
    var request = $.ajax({
        url: '/inventory/supplier_replacement/details/DownloadSupRet',
        method:'post',
        data: {
            hrd_id : '{{.Tconf.hdr_id}}' ,
            checkbox_id : checkValues[i] , 
            qty : $('#'+checkValues[i]).val() ,
        },
        success: function (data) {

            console.log(data[0]);
            var htdata  = '<div class="alert alert-danger"> Error: </div>';
            if(parseInt(data[0])>0){
                htdata  = '<div class="alert alert-success"> Success: ID # '+data[0]+' </div>';
            }else{
                htdata  = '<div class="alert alert-danger">'+data[1]+'</div>';
                errorcount +=1
            } 
            $( ".errorDv" ).append(htdata)
        }
    })

    promises.push(request);
}

1 个答案:

答案 0 :(得分:1)

If you want to make one request after another you can reduce your checkValues to one promise:

var promises = [];
checkValues.reduce(
  function(p,checkValue){
    p.then(
      function(results){
        $.ajax({
          url: '/inventory/supplier_replacement/details/DownloadSupRet',
          method: 'post',
          data: {
            hrd_id: '{{.Tconf.hdr_id}}',
            checkbox_id: checkValue,
            qty: $('#' + checkValue).val(),
          }
        })
        .then(
          function (data) {
            return results.concat([data]);
          }
        )
        .catch(
          function(err){
            //an error with the connection or server error
            return results.concat([err])
          }
        )
        .then(
        )
      }
    )
  },
  $.Deferred().resolve([])//assuming no native promises or polyfil
)
.then(//all results came in
  function(results){
    results.forEach(
      function(result){
        console.log(result[0]);
        var htdata = '<div class="alert alert-danger"> Error: </div>';
        if (parseInt(result[0]) > 0) {
          htdata = '<div class="alert alert-success"> Success: ID # ' + result[0] + ' </div>';
        } else {
          htdata = '<div class="alert alert-danger">' + result[1] + '</div>';
          errorcount += 1
        }
        $(".errorDv").append(htdata);    
      }
    );
  }
);

If you want to perform all requests at once you can use Promise.all or $.when:

var promises = [];
$.when.apply(//when takes arg1,arg2... but with apply we can pass args as array
  $,
  checkValues.map(
    function(checkValue){
      $.ajax({
        url: '/inventory/supplier_replacement/details/DownloadSupRet',
        method: 'post',
        data: {
          hrd_id: '{{.Tconf.hdr_id}}',
          checkbox_id: checkValue,
          qty: $('#' + checkValue).val(),
        }
      })
      .catch(
        function(err){
          //an error with the connection or server error
          return err
        }
      )
    }
  )
)
.then(//all results came in
  function(results){
    results.forEach(
      function(result){
        console.log(result[0]);
        var htdata = '<div class="alert alert-danger"> Error: </div>';
        if (parseInt(result[0]) > 0) {
          htdata = '<div class="alert alert-success"> Success: ID # ' + result[0] + ' </div>';
        } else {
          htdata = '<div class="alert alert-danger">' + result[1] + '</div>';
          errorcount += 1
        }
        $(".errorDv").append(htdata);    
      }
    );
  }
);