Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
69
rated 0 times [  73] [ 4]  / answers: 1 / hits: 7903  / 4 Years ago, sun, may 31, 2020, 12:00:00

I have a situation I want to use await in a ternary operator. I want to set a value to either a literal value or the resolve value of a promise, depending on a condition. Hopefully the code below will help describe what I want to do, but I am pretty sure it is not correct so consider it pseudo code.



const val = checkCondition ? literal value : await promiseGetValue();


Where promiseGetValue() returns a promise which resolves to a literal value. What is the correct way to do this?


More From » async-await

 Answers
16

This is actually a valid syntax, just for clarity u can surround the await promiseGetValue() with brackets. here is a demo of this syntax.





const returnPromise = () => Promise.resolve('world')
const f = async () => {
const x = true ? 'hello' : await returnPromise()
const y = false ? 'hello' : await returnPromise()
console.log(x,y)

}
f()




[#3622] Friday, May 29, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
matteo

Total Points: 81
Total Questions: 100
Total Answers: 96

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
matteo questions
Tue, Mar 8, 22, 00:00, 2 Years ago
Thu, Mar 12, 20, 00:00, 4 Years ago
Tue, Jan 22, 19, 00:00, 5 Years ago
Wed, Sep 12, 18, 00:00, 6 Years ago
Sun, Jul 29, 18, 00:00, 6 Years ago
;