我有一个功能:
checkIfReadyToUse(){
return this.af.object("/cardReady").query.once("value").then(data => data.val());
}
我想用来获取cardReady的值。问题是当我使用该函数时,它会像这样返回,而不是true或false:
ZoneAwarePromise {_
_zone_symbol__state: null,
_zone_symbol__value:
如何使它返回cardReady的值而不是该区域符号?
答案 0 :(得分:1)
在不知道data.val()
返回什么的情况下,我的假设是您没有在执行.then()
时执行await
或checkIfReadyToUse
,因为它也会返回一个承诺
const result = await checkIfReadyToUse()
console.log(result)
或
checkIfReadyToUse().then((result) => console.log(result))
取决于您使用的是.then()
还是async/await
语法
答案 1 :(得分:0)
获取承诺的已解决值的最佳方法是将其await
放在async
函数中。
const resolveTrue = () => Promise.resolve(true)
const resolveFalse = () => Promise.resolve(false)
;(async () => {
if (await resolveTrue()) console.log('this logs')
if (await resolveFalse()) console.log('this doesn’t')
if (resolveFalse()) {
console.log('this logs, because we forgot to await (an un-awaited Promise is truthy)')
}
})()
您也可以在返回的承诺中致电.then
:
functionReturningPromise().then(result => { /* do stuff with result */ })
但是,async/await
通常更好,原因有两个:
.then
链可能会成为“回调地狱”的新版本)。此外:我不确定Angular的ZoneAwarePromise
是否建立在原生的Promise之上,但请注意,async/await
甚至可以用于非原生Promise ,只要它们实现then
able protocol。例如:
const FakePromise = (val) => {
return { then: cb => setTimeout(() => cb(val), 1000) }
}
;(async () => {
const result = await FakePromise('val')
console.log(result) // this works! ?
})()