Javascript 承诺是否及时成为有条件承诺的一部分
我需要测试一个承诺的结果。承诺会及时成为有条件承诺的一部分吗Javascript 承诺是否及时成为有条件承诺的一部分,javascript,promise,Javascript,Promise,我需要测试一个承诺的结果。承诺会及时成为有条件承诺的一部分吗 if (myPromise() > 15 && myOtherPromise()) { // do stuff when myPromise resolves to over 15 and myOtherPromise is true } else { // do stuff when myPromise resolves to 15 or less or myOtherPromise is fa
if (myPromise() > 15 && myOtherPromise()) {
// do stuff when myPromise resolves to over 15 and myOtherPromise is true
} else {
// do stuff when myPromise resolves to 15 or less or myOtherPromise is false
}
还是我只需要接受它然后做:
let myP = myPromise();
let myOtherP = myOtherPromise();
promise.all([myP, myOtherP]).then(function(res) {
if (res[0] > 15 && res[1]) {
// do stuff when myPromise resolves to over 15 and myOtherPromise is true
} else {
// do stuff when myPromise resolves to 15 or less or myOtherPromise is false
}
});
从下面的评论转载给大家“否决”这个问题,并认为这是一个重复
好吧,是和否。不,因为我和Jasmine一起工作,当一个承诺通过时,expect调用自动解决一个承诺<代码>期望(myPromise())。比(15)更高。。因此,从外部来看,可以想象if的条件可能会在执行任何比较之前解决承诺
假设
myPromise
和myOtherPromise
是返回代码似乎指示的承诺的函数,则不可以:
if (myPromise() > 15 && myOtherPromise()) {
承诺是目标。因此,如果myPromise()
返回承诺,那么:
if (myPromise())`
始终是真实的,并且if
语句与承诺的最终解决价值完全无关。因此,第一个if
语句将不会检查任一承诺的解析值
如果要查看促销的解析值,必须使用
.then()
或.all()
之类的方法来获取解析值。没有其他方法可以访问已解析的值
如果要检查myPromise()
和myOtherPromise()
的已解析值,则必须等待这两个值解析,并且应使用Promise.all()
,如第二个代码示例所示:
Promise.all([myPromise(), myOtherPromise()]).then(function(results) {
if (results[0] > 15 && results[1]) {
// got the result we wanted
}
}).catch(function(err) {
// error here
});
您无法知道(这是异步的e点)。只是“吸起来”或者调用回调函数好吧,是和否。不,因为我在和Jasmine一起工作,当一个承诺被传递时,expect调用会自动解析一个承诺<代码>期望(myPromise())。比(15)更高。。因此,从外部来看,可以想象if的条件可能会在执行任何比较之前解析承诺。@Machtyn
if
和其他控制流构造不支持承诺。有异步版本是很有意思的,但我不知道有什么建议。这到底是怎么一个重复的标记。我一点也看不出来。这是一个关于访问一对承诺的解析值的具体问题,而这不是另一个问题所涉及的。@Machtyn Jasmine可能很神奇,但如果不是的话,。是的,我应该意识到当我做myOtherPromise()时,我应该做myOtherPromise()==在我的“坏”中为真例如。@Machtyn-huhhmyOtherPromise()==true
对你也没有任何好处。承诺是一个目标。您只能通过类似p.then()
或Promise.all([p1,p2])
的方式获取其值。用if(p)
@Machtyn永远无法得到它的值-一个if
语句就是普通的Javascript。一些测试框架不会也不能更改if
语句的工作方式。对。这就是为什么我说我的“坏”例子。@Machtyn-那么,这回答了你的问题吗?