【问题标题】:Make function return the result of a promise inside of it使函数返回它内部的承诺的结果
【发布时间】:2020-12-28 22:13:44
【问题描述】:

我有一个函数:

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 的值而不是这个区域符号?

【问题讨论】:

  • 可以分享一下你是如何使用checkIfReadyToUse的吗?
  • .then(data => return data.val());
  • @PatricNox 和他一样,只是写法更冗长
  • this.loyaltyCardReady = this.promotionService.checkIfReadyToUse();像这样
  • 是的,看看我的回答

标签: javascript angular firebase-realtime-database promise


【解决方案1】:

获得 promise 的解析值的最佳方法是在 async 函数中 await 它。

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)')
    }
})()

您也可以在返回的 Promise 上调用 .then

functionReturningPromise().then(result => { /* do stuff with result */ })

但是,async/await 通常更好,原因有两个:

  1. 它往往更具可读性(.then 链如果太多,可能会成为新版本的“回调地狱”)。
  2. You'll get better stack traces(如果您的转译目标支持)。

另外:我不确定 Angular 的 ZoneAwarePromise 是否建立在原生 Promise 之上,但请注意 async/await 可以使用即使在非原生 Promise 上,只要因为他们实现了thenable protocol。例如:

const FakePromise = (val) => {
    return { then: cb => setTimeout(() => cb(val), 1000) }
}

;(async () => {
    const result = await FakePromise('val')

    console.log(result) // this works! ?
})()

【讨论】:

  • 为什么这是最好的方法?
  • 我认为没有最好或更坏。但是语法糖 async/await 的存在是有原因的:没有回调地狱,也没有“永无止境”的承诺链。简而言之:它更容易阅读。
  • @PatricNox 首先,它往往更具可读性(.then 链如果太多,可能会成为“回调地狱”的新版本)。而且,because you'll get better stack traces(如果您的转译目标支持它)。
【解决方案2】:

在不知道data.val() 返回什么的情况下,我的假设是您没有在执行checkIfReadyToUse 时执行.then()await,因为它也会返回一个promise。

const result = await checkIfReadyToUse()
console.log(result)

checkIfReadyToUse().then((result) => console.log(result))

取决于您使用的是.then() 还是async/await 语法

【讨论】:

    猜你喜欢
    • 2021-08-15
    • 2020-03-06
    • 2016-08-08
    • 2019-07-09
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    相关资源
    最近更新 更多