Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在JQuery';递延美元()?_Javascript_Jquery_Promise - Fatal编程技术网

Javascript 如何在JQuery';递延美元()?

Javascript 如何在JQuery';递延美元()?,javascript,jquery,promise,Javascript,Jquery,Promise,我以为fail()会阻止错误传播,但这似乎没有发生。以下是我所拥有的: someAsynTask() .then(function(){ 1/0; }) .fail(function(){ console.log('Error handled.'); }) .then(function(){ console.log('test'); // not printed (expected it to print) }) .fail(function(

我以为
fail()
会阻止错误传播,但这似乎没有发生。以下是我所拥有的:

someAsynTask()
  .then(function(){
    1/0;
  })
  .fail(function(){
    console.log('Error handled.');
  })
  .then(function(){
    console.log('test'); // not printed (expected it to print)
  })
  .fail(function(){
    console.log('More errors?'); // printed (nor expecting it to print)
  });

如何使
fail()
捕获错误以防止它沿着承诺链传播?

jQuery有两件事,最多2.x

  • 承诺不是“安全的”
  • 存在
    .fail()
    处理程序不会导致下游承诺标记为“已处理”
只有
.then()
具有“过滤”功能,但即使使用
.then()
,过滤也不是自动的

从3.0开始,我们被告知jQuery承诺将符合承诺/A+的要求

1.x和2.x的行为是完全可预测的,甚至是可爱的,只是与A+不同。以下代码应给出您期望的行为:

someAsynTask().then(function(){
    try {
        1/0;
    } catch(e) {
        return $.Deferred().reject(e).promise(); // Returning a rejected promise from a then()'s success handler is the only way to transmogrify success into failure. An uncaught `throw` does not have the same effect in jQuery 1.x and 2.x.
    }
}).then(null, function(){
    var message = 'Error handled';
    console.log(message);
    return $.when(message); //Returning a resolved promise from a then()'s fail handler is the only way to transmogrify failure into success in jQuery 1.x and 2.x.
}).then(function(msg) {
    console.log(msg); // should print 'Error handled' again
}).fail(function() {
    console.log('More errors?'); // should not print. Also, no filtering here. `.fail()` does not possess filtering power.
});

除以0不会在JSI中引发任何错误。我认为这将帮助您了解发生了什么。这里最大的问题是jQuery不像native/A+承诺那样处理异常。因此,如果抛出异常,fail甚至不会被调用
fail
根本不返回新的承诺,它只是附加回调并返回原始承诺。没有“传播”和“链条”,只有被拒绝的旧承诺。您正在查找
。然后(null,function(){console.log(“error handled”);})
(但请参见@elio.ds comment)或:过滤能力是什么意思?您将看到在中,作为回调传递的函数称为“doneFilter”、“failFilter”和“progressFilter”。它们被称为过滤器,因为它们有能力影响沿着链条传播的承诺。
.done()
.fail()
.progress()
方法不具备此功能。