jQuery Promise - 即使有些json没有找到,也会启动

时间:2018-01-18 15:52:17

标签: javascript jquery promise

我使用诺言,但有时候我不能在一种情况下从各种原因获得JSON,即使缺少一些JSON,我怎么能开始完成,这个代码是我现在的#39 ; m只有失败的消息

$.when(
    arrayResults[0] ? $.getJSON("url") : null,
    arrayResults[1] ? $.getJSON("url") : null,
    arrayResults[2] ? $.getJSON("url") : null

).done(function () { }).fail(function () {
    console.log('Failed');
});

2 个答案:

答案 0 :(得分:0)

您可以使用deferred.always(cb)

$.when(
    arrayResults[0] ? $.getJSON("url") : null,
    arrayResults[1] ? $.getJSON("url") : null,
    arrayResults[2] ? $.getJSON("url") : null
)
.done(function () { console.log('I will run when the promise was resolved') })
.fail(function () { console.log('I will run when the promise was rejected') })
.always(function() { console.log('I will always fire, regardless of previous results') })

请在此处查看更多信息:https://api.jquery.com/deferred.always/

答案 1 :(得分:0)

如果您使用的是jQuery v3 +,它符合Promises A+,因此您可以将catch()添加到请求承诺

每当你从一个catch中返回时它会解析先前的promise并将你返回的任何内容传递给promise链中的下一个then()



function getData(url){
  return $.getJSON(url)
     .then(data=>data)
     .catch(resolveFailure)

}

function resolveFailure(jqXhr) { 
  // return whatever you want here. I added the status in case that is of interest
  // could return `false` or string or whatever
  // can also log any issues back to server if needed
  return {
    error: true,
    status: jqXhr.status,
    statusText: jqXhr.statusText
  };
}


var req = getData('https://api.myjson.com/bins/l9ywp'),
    req2 = getData('https://httpbin.org/FAIL'),
    req3 = getData('https://api.myjson.com/bins/l9ywp');

// could also replace `$.when with `Promise.all()`
$.when(req, req2, req3).then(function(r1, r2, r3) {
  // validate the arguments based on whatever you return in the catch()
  console.log('r1', r1);
  console.log('r2', r2);// object returned from catch()
  console.log('r3', r3);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
&#13;
&#13;
&#13;