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
// ❌ Hard to read and maintaingetUser(id,(err,user)=>{getPosts(user.id,(err,posts)=>{getComments(posts[0].id,(err,comments)=>{getAuthor(comments[0].authorId,(err,author)=>{console.log(author);// buried 4 levels deep!});});});});
Promises
// Create a promiseconstpromise=newPromise((resolve,reject)=>{constsuccess=true;if(success)resolve("Data fetched!");elsereject(newError("Failed!"));});// Consumepromise.then(data=>console.log(data))// on resolve.catch(err=>console.error(err))// on reject.finally(()=>console.log("Done"));// always runs// Promise chaining (fixes callback hell)fetchUser(id).then(user=>fetchPosts(user.id)).then(posts=>fetchComments(posts[0].id)).then(comments=>console.log(comments)).catch(err=>console.error(err));// Promise combinatorsPromise.all([p1,p2,p3])// wait for ALL, fail-fastPromise.allSettled([p1,p2,p3])// wait for ALL (never rejects)Promise.race([p1,p2,p3])// first to settle winsPromise.any([p1,p2,p3])// first to RESOLVE wins
async / await (ES2017)
// async function always returns a PromiseasyncfunctionfetchUser(id){try{constresponse=awaitfetch(`/api/users/${id}`);if(!response.ok)thrownewError(`HTTP ${response.status}`);constdata=awaitresponse.json();returndata;}catch(err){console.error("Error:",err);throwerr;// re-throw to caller}}// Parallel execution (don't await sequentially if independent!)asyncfunctionloadAll(){// ❌ Sequential (slow — waits for each)constuser=awaitfetchUser(1);constposts=awaitfetchPosts(1);// ✅ Parallel (fast — both start at once)const[user2,posts2]=awaitPromise.all([fetchUser(1),fetchPosts(1)]);}