简体   繁体   English

q库承诺向完成的方法传递一个值

[英]q library promises passing a value to done method

I'm trying to find the purpose as well as how to use done method of the q library promises, if done can receive a value or function via resolve or reject , can someone explain how done method is called and how can pass any arguments to it? 我正在尝试查找q库承诺的目的以及如何使用完成的方法,如果done可以通过resolvereject接收值或函数,可以有人解释done方法的调用方式以及如何将任何参数传递给它?

Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
    // Do something with value4
})
.catch(function (error) {
    // Handle any error from all above steps
})
.done();

In promises, whatever you resolve your deferred with, is the argument that get's passed to done or then . 在Promise中,无论您解决什么延迟的问题,都是传递给donethen You can change the resolve value inside of a resolved handler by returning a different value. 您可以通过返回不同的值来在已解析的处理程序中更改解析值。 Like so 像这样

Q.fcall(promisedStep1)
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
  // Do something with value4
  return 'tada!';
})
.catch(function (error) {
    // Handle any error from all above steps
})
.done(function(differentValue) {
  console.log(differentValue); // outputs "tada!"
});

The actual purpose of .done in Q is to handle errors so errors won't get suppressed. Q中.done的实际目的是处理错误,以使错误不会被抑制。

If you have a rejected promise chain in Q, if you use .then all the way it becomes a silent failure, so the following code: 如果您在Q中的承诺链被拒绝,则如果使用.then ,那么它会变成无声失败,因此以下代码:

Q().then(function(){
    var val = JSON.prase(data);
    someEffectWith(val);
});

Is a silent failure, did you note the typo? 是无声的失败,您注意到错字了吗? Because there is never a way to know when the chain has ended it is crucial to use .done to let the library know: 由于永远无法知道链何时结束,因此使用.done来告知库至关重要:

Q().done(function(){
    var val = JSON.prase(data);
    someEffectWith(val);
});

Or: 要么:

Q().then(function(){
    var val = JSON.prase(data);
    someEffectWith(val);
}).done();

Will both echo a big red warning to your console, notifying you of the error. 两者都会向您的控制台回显一个红色大警告,以通知您该错误。 As for how it's called it has the exact same arguments of .then only it does not return a promise, instead it returns undefined so you know you can't chain to it (it terminated the chain). 至于它的调用方式,它具有与。完全相同的参数.then仅不返回promise,而是返回undefined因此您知道无法链接到它(它终止了链接)。

It's worth mentioning some promise libraries, as well as native promises in firefox do this for you and you don't need to use .done in those libraries - the error will get logged regardless. 值得一提的是一些promise库,以及firefox中的本机promise可以为您做到这一点,并且您无需在这些库中使用.done -无论如何都会记录错误。

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

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