繁体   English   中英

jQuery $。当不等待承诺解决时,拒绝

[英]Jquery $.when not waiting for promises to resolve, reject

我有一个动态的API调用数组,需要出去。 但是,jQuery的$ .when似乎没有在等待promise的解决或被拒绝,或者我不了解如何正确使用promise。

function addEntry(data) {
  return new Promise(function(resolve, reject) {
    _customAPIClass_.post('some/url/path', data)
      .done(function(){
        console.log('resolving');
        resolve(1000)
      })
      .catch(function(){
        console.log('rejecting');
        reject(2000);
      })
  });
}

let deferreds = [];

$.each(form.find(el), function(i, element) {
  let data = {
    id: $(element).find('.id').val(),
    name: $(element).find('.name').val()
  }
  deferreds.push(addEntry(data));
}

if (deferreds.length) {
  $.when.apply(deferreds).then(function(data){
    console.log('All done', data)
  }, function(err){
    console.log('error', err);
  });
}

控制台输出 .then()执行后,两个api调用拒绝promise 控制台输出

因此,我不理解的是什么,而Stack Overflow或jQuery文档上还有其他哪些问题没有帮助我解决,那就是为什么.then()行为在API调用完成并解决之前一切正常还是拒绝了他们的诺言? 在完成所有API调用后,我该如何处理解决或拒绝问题,还是我误解了.when()和promises的目的?

更改:

$ .when.apply(递延)

至:

$ .when.apply($,递延)

如此处所述: https : //medium.com/sungthecoder/making-multiple-ajax-calls-and-deciphering-when-apply-array-b35d1b4b1f50,并在Kevin B的评论中提到:

“当我们调用$ .when()函数时,该函数内部的'this'关键字将隐式绑定到jQuery对象。但是,当我们调用$ .when.apply()时,我们必须将'this'关键字显式绑定到某些对象。并且我们知道绑定必须与jQuery对象一起进行,因此我们将jQuery对象(也称为$)作为第一个参数。”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM