Awaiting Non-Promise Values
What you'll learn: You can use await on regular, non-promise values, and JavaScript will handle them gracefully without errors.
The Surprising Flexibility of Await
You might think await only works with promises, but JavaScript is more forgiving than that. When you await a value that isn't a promise, JavaScript immediately wraps it in a resolved promise and continues execution. This means await is safe to use on any value.
Here's what happens:
async function demo() {
const number = await 42;
console.log(number); // 42
const text = await "hello";
console.log(text); // "hello"
}
These lines execute synchronously and immediately. JavaScript essentially treats await 42 as if you wrote await Promise.resolve(42).
Why This Matters
This flexibility is useful when you have conditional code paths where a value might be a promise or might not be:
async function process(data) {
// data could be a promise or a plain value
const resolved = await data;
return resolved * 2;
}
// Both work fine:
process(Promise.resolve(5)); // returns promise for 10
process(5); // returns promise for 10
You don't need to check whether something is a promise before awaiting it. The await keyword handles both cases uniformly.
The Mental Model
Think of await like a universal adapter: if you plug in a promise, it waits for resolution. If you plug in a regular value, it passes right through without delay. This makes your async code more robust and easier to write.
Key Takeaway: await works on any value, not just promises—non-promise values are immediately resolved, making await a safe, universal way to handle potentially asynchronous values.