shad0w_wa1k3r
shad0w_wa1k3r

Reputation: 13372

Placement of the await operator

I was wondering about the flexibility of the await operator in JavaScript. Specifically, how and where can we use it within an expression (inside an async function).

e.g.

!await Promise.resolve(10);
await !Promise.resolve(10);

Which of the above two (or both?) are valid & which is more "conventional"? The expected return value of the expression is !10.

For generalising, you can substitute any other kind of expressions / operations in place of the !.

Also, is the following valid & appropriate (in terms of programming practices)?

for (const i=0; i < await Promise.resolve(10); i++) {...}

And is there an in-depth official documentation for this that I can refer to?

Upvotes: 4

Views: 104

Answers (3)

Mark
Mark

Reputation: 92440

for (const i=0; i < Promise.resolve(10); i++)

The value of Promise.resolve(10) is a promise, not a number. As a result the comparison of i < Promise.resolve(x) will always be false, so will i > Promise.resolve(x) because you are comparing with NaN.

// all comparisons with NaN are false
console.log(10 < Promise.resolve(1))
console.log(10 > Promise.resolve(1))
console.log(10 == Promise.resolve(1))
console.log(Promise.resolve(1) == Promise.resolve(1))

You simply can't use a promise this way outside of an async function. You could do this (that's not a recommendation):

async function test(){
    for (let i = 0; i < await Promise.resolve(10); i++){
        console.log(i)
    }
}
test()

Similarly, !Promise.resolve(10) will get the result of not some promise rather than not 10. But awaiting the result works as expected, because then you are comparing a number.

Upvotes: 2

Tarek Essam
Tarek Essam

Reputation: 4010

In the for loop the expression i < Promise.resolve(10) will always be false because Promise.resolve(10) is an object so the loop body will never be executed.

Upvotes: 0

Kevin
Kevin

Reputation: 25269

Firstly, Promise.resolve(10) returns a promise that immediately resolves to the value 10.

Secondly, you always need to await a promise from inside an async function.

So I don't think any of your examples make much sense, aside from maybe !await Promise.resolve(10);, assuming you want to essentially do !10.

In your for loop example, for (const i=0; i < Promise.resolve(10); i++) {...}, what you're doing is comparing a promise to a number, which doesn't make sense. You'd need to await the promise first.

Upvotes: 1

Related Questions