Promise-based JavaScript code often has to wait for an API call, file read, timer, or other asynchronous result before the next line can use the value. async and await keep that dependent code in top-down order while still using promises behind the scenes.
Related: Fetch JSON with JavaScript
Related: Cancel a fetch request with AbortController
Related: Handle JavaScript errors with try-catch
An async function always returns a promise, even when the function body returns a plain value. Inside that function, await pauses only the async function's continuation until the awaited value settles, so the surrounding page or process can continue handling other work.
Rejected promises behave like thrown errors at the await line. Put the awaited call inside try and catch when the same function should convert a failure into a controlled message, fallback value, or user-visible error state.
function getProfile(userId) { if (userId === 0) { return Promise.reject(new Error("profile API unavailable")); } return Promise.resolve({ id: userId, name: "Aisha" }); } async function loadProfile(userId) { try { const profile = await getProfile(userId); return `Loaded ${profile.name}`; } catch (error) { return `Request failed: ${error.message}`; } } console.log(await loadProfile(42)); console.log(await loadProfile(0));
The .mjs extension makes the file a JavaScript module, which allows the two top-level await calls at the end of the file. In a regular script, use await inside another async function instead.
async function loadProfile(userId) { const profile = await getProfile(userId); return `Loaded ${profile.name}`; }
await returns the fulfilled value from getProfile(), so profile.name is read from the resolved object rather than from the promise itself.
try { const profile = await getProfile(userId); return `Loaded ${profile.name}`; } catch (error) { return `Request failed: ${error.message}`; }
A rejected promise at the await line enters catch the same way a thrown error would. This prevents the rejected case from becoming an unhandled promise rejection.
$ node async-await-demo.mjs Loaded Aisha Request failed: profile API unavailable
$ rm async-await-demo.mjs