JS promises Flashcards
How to write a promise
const doWork = new Promise((resolve,reject)=>{ const a = 1; if(a === 1){ setTimeout(()=>{ resolve([3,4,5]) },5000) }else{ setTimeout(()=>{ reject("Oops") },5000) }
});
doWork.then((result)=>{ console.log(result) }).catch((error)=>{ console.log(error) });
When does a promise stop running?
When either resolve or reject is called. resolve and reject acts like a return statement
How do promises work?
When a promise is called, it is considered pending. Once the pending promise resolves it is considered fullfilled. When it is not resolved it is considered rejected.
What is promise chaining?
Chaining multiple promises together
Avoids callback hell or nested and duplicate code
How to chain promises?
const sum = (x,y)=>{ return new Promise((resolve,reject)=>{ setTimeout(()=>{ resolve(x + y) },3000) }) };
sum(5,5).then((result)=>{ return sum(result,5) }).then((result)=>{ return sum(result,5) }).then((result)=>{ console.log(result) }).catch(e=>{ console.log(e) });
What is Async/Await?
A tool that makes it easier to work with promises. It provides a syntactical advantage, making code more readible, by avoiding promise chaining, and it keeps all variables within the same scope, which makes it easier to access their values