Fabio100 ola
Fabio100 ola

Reputation: 31

Make function return the result of a promise inside of it

I have a function:

checkIfReadyToUse(){
 return this.af.object("/cardReady").query.once("value").then(data => data.val());
  }

That i want to use to get the value of cardReady. The problem is when i use that function, it returns like this and not true or false:

ZoneAwarePromise {_
_zone_symbol__state: null, 
_zone_symbol__value: 

How can i make that it returns the value of cardReady and not this zone symbol?

Upvotes: 0

Views: 292

Answers (2)

Lionel Rowe
Lionel Rowe

Reputation: 5926

The best way to get the resolved value of a promise is to await it inside an async function.

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

You can alternatively call .then on the returned promise:

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

However, async/await is typically better for two reasons:

  1. It tends to be more readable (.then chains can become the new version of "callback hell" if you have too many of them).
  2. You'll get better stack traces (if your transpilation target supports it).

Aside: I'm not sure if Angular's ZoneAwarePromise is built on top of native promises or not, but note that async/await can be used even on non-native Promises, as long as they implement the thenable protocol. For example:

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

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

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

Upvotes: 0

andy mccullough
andy mccullough

Reputation: 9571

Without knowing what data.val() returns, my assumption is that you are not doing a .then() or await on the execution of checkIfReadyToUse, as it will return a promise also.

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

or

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

depending if you use the .then() or async/await syntax

Upvotes: 1

Related Questions