为什么Q.js在解决后承诺异步? [英] Why are Q.js promises asynchronous after they have been resolved?

查看:76
本文介绍了为什么Q.js在解决后承诺异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有以下内容:

var deferred = Q.defer();

deferred.resolve();

var a = deferred.promise.then(function() {
    console.log(1);    
});

console.log(2); 

...为什么我在控制台中看到2,然后是1?

...why do I see 2, then 1 in the console?

据我所知,根据Promises规范这个输出是正确的,该规范说明在下一个tick上调用该函数(例如 setTimeout()),即使它已经解决了,但我不明白为什么。

I understand this output is correct according to the Promises spec, which says to call the function on the next tick (e.g. setTimeout()), even if it is already resolved, but I don't understand why.

我希望代码调用同步一系列承诺。

I would like to have code that calls then on a series of promises synchronously, assuming that all the promises have been resolved.

我的真实用例是我试图使用Angular的实现, $ q ,我希望所有的然后回调在同一个<$ c $中执行c> $ digest 循环,这样我就不会得到不必要的后续 $ digest 循环。

My real use case is that I am trying to use Angular's implementation, $q, and I want all of the then callbacks to execute in the same $digest cycle, so that I don't get unnecessary subsequent $digest cycles.

推荐答案

答案是一致性。

在实际代码中,您没有始终<的承诺/ em>在创建时立即解决,它们将毫无意义。所以你承诺有时可以立即解决。

In real code, you don't have promises that are always immediately resolved when created, they would be pointless. So you have promises that sometimes may be immediately resolved.

在这种情况下,你不希望有不同的流程。你想要总是相同的,可预测的流程。因此,您希望下一个函数在下一个时间点始终调用。

In that case, you don't want to have a different flow. You want always the same, predictable flow. So you want the next function to be always called on next tick.

当您不需要时,请不要使用承诺。

Don't use a promise when you don't need one.

这篇关于为什么Q.js在解决后承诺异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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