Skip to content

Instantly share code, notes, and snippets.

@Nagibaba
Created November 15, 2023 18:02
Show Gist options
  • Save Nagibaba/b45ad65239ef35db8252cb35e46e3159 to your computer and use it in GitHub Desktop.
Save Nagibaba/b45ad65239ef35db8252cb35e46e3159 to your computer and use it in GitHub Desktop.
Javascript Promise simple examples
const sumPromise = (a,b) => {
const p = new Promise((resolve, reject) =>{
if(typeof a === 'number' && typeof b === 'number'){
resolve(a+b)
} else {
reject(new Error('Tip düzgün deyil'))
}
})
return p
}
const timerPromise = (time=1000, name) =>{
const p = new Promise((resolve, reject) =>{
setTimeout(()=>{
if(name!=='p1')
resolve(name)
else reject('P1 not found')
}, time)
})
return p
}
// Pending
const p1 = sumPromise(3,5)
const p2 = sumPromise('4',4) // here is an error
const p3 = sumPromise(100,200)
const t1 = timerPromise(100, 'p1') // here is an error
const t2 = timerPromise(2000, 'p2')
const t3 = timerPromise(1000, 'p3')
Promise.race([p1,p2,p3])
.then(val => console.log(val)) // fullfilled
.catch(err => console.warn(err)) // rejected
// .all hamısı fullfilled olmalıdır
// .allSettled hamısı settled olduqdan sonra
// .race İlk cavabı qaytar (xəta olsa belə)
// .any ilk fullfilled olanı qaytar
const getSum = async() =>{
try{
const p2 = sumPromise(5,4)
const p3 = sumPromise(100,200)
const p1 = sumPromise(30,50)
const allCorrect = Promise.all([p2, p3, p1])
console.log(allCorrect)
}catch(err){
console.warn(err.message)
}
}
getSum()
const getTimerAsync = async function(){
const timer = await timerPromise(1000, 'timer')
console.log(timer)
}
getTimerAsync()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment