延迟方法中不会抛出错误 [英] Error is not thrown inside a deferred method

查看:154
本文介绍了延迟方法中不会抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释为什么我的错误不会在我的第一个例子中抛出?为什么我使用 process.nextTick()

  var deferred = require('deferred'); 

//此代码无效。
//错误似乎从来没有被抛出,脚本类型的冻结没有说什么。
deferred.resolve()。then(function(){
console.log('deferred resolved');
throw new Error('在同步错误中抛出deferred.then()') ;
});

//此代码可以正常工作。
//我刚刚在process.nextTick()方法中嵌入了throw。
deferred.resolve()。then(function(){
console.log('deferred resolved');
process.nextTick(function(){
throw new Error 'deferred.then()'中抛出同步错误);
});
});

为什么我需要等待nextTick在之内抛出一个错误() ...



任何解释将不胜感激。
Thx



我看过这篇文章(在延迟回调中没有抛出/显示错误)。但是它只给了一半的答案...

解决方案

deferred的行为在你的情况下对我来说似乎是合理的。



在第二种情况下,我不认为延期有一种方法来捕捉 nextTick 回调中抛出的错误。所以错误被抛出。



在第一种情况下, deferred 抓住它,并认为在失败的状态。 deferred 文档指出,如果您希望它有效地将承诺推送到失败状态的错误,您必须调用完成

  deferred.resolve()。then(function(){
console.log ');
抛出新的错误('在deferred.then()'中抛出的同步错误);
})。done();

请参阅 https://github.com/medikoo/deferred#ending-chain 文档


Can somebody explain to me why my error is not thrown in my first example? And why it is when I use process.nextTick() ?

var deferred = require('deferred');

// This code does not work. 
// Error seems to never been thrown and script kind of freeze without saying anything.
deferred.resolve().then(function(){
    console.log('deferred resolved');
    throw new Error('Synchronous error thrown in deferred.then()');
});

// This code does work. 
// I just embedded the throw in the process.nextTick() method.
deferred.resolve().then(function(){
    console.log('deferred resolved');
    process.nextTick(function(){
        throw new Error('Synchronous error thrown in deferred.then()');
    });
});

Why do I need to wait the nextTick to throw an error inside the then() ...

Any explanation will be appreciated. Thx

I have seen this post (No errors thrown/displayed when in a deferred callback). But it gives only half an answer ...

解决方案

The behavior of deferred seems reasonable to me in your cases.

In the second case, I don't think that deferred has a way to catch the error thrown in the nextTick callback. So the error is thrown.

In the first case, deferred catches it and considers that that resulting promise in in failed state. The deferred documentation states that if you want it to effectively throw an error that pushed the promise into failed state, you have to call done

deferred.resolve().then(function(){
  console.log('deferred resolved');
  throw new Error('Synchronous error thrown in deferred.then()');
}).done();

See https://github.com/medikoo/deferred#ending-chain for documentation

这篇关于延迟方法中不会抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆