You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
UnhandledPromiseRejectionWarning: Error: ...
SyntaxError: await is only valid in async functions
TypeError: Cannot read property of undefined (from unresolved promise)
// ❌ Forgot await — user is a Promise, not a user objectasyncfunctiondisplayUser(id){constuser=getUser(id);// ❌ no awaitconsole.log(user.name);// [object Promise].name → undefined}// Await the promiseasyncfunctiondisplayUser(id){constuser=awaitgetUser(id);// console.log(user.name);}
Solution 2: Error Handling in Async Functions
// ❌ Unhandled rejection crashes the processasyncfunctionloadData(){constdata=awaitfetch('/api/data').then(r=>r.json());returndata;}// With try/catchasyncfunctionloadData(){try{constresponse=awaitfetch('/api/data');if(!response.ok)thrownewError(`HTTP ${response.status}`);returnawaitresponse.json();}catch(err){console.error('loadData failed:',err.message);throwerr;// re-throw so caller can handle}}// In Express: use async wrapper to forward errorsconstasyncHandler=fn=>(req,res,next)=>Promise.resolve(fn(req,res,next)).catch(next);router.get('/users',asyncHandler(async(req,res)=>{constusers=awaitUser.findAll();res.json(users);}));
Solution 3: Parallel Async Operations
// ❌ Sequential — takes 3 seconds if each takes 1sasyncfunctionloadDashboard(){constuser=awaitgetUser();// 1sconstposts=awaitgetPosts();// 1sconstfriends=awaitgetFriends();// 1sreturn{ user, posts, friends };}// Parallel — takes 1 second totalasyncfunctionloadDashboard(){const[user,posts,friends]=awaitPromise.all([getUser(),getPosts(),getFriends(),]);return{ user, posts, friends };}// Promise.allSettled — don't fail if one rejectsconstresults=awaitPromise.allSettled([getUser(),getPosts(),getFriends(),]);constsuccessful=results.filter(r=>r.status==='fulfilled').map(r=>r.value);
Prevention
Enable no-floating-promises ESLint rule with TypeScript
Always add global handler: process.on('unhandledRejection', console.error)