What is a Promise?

Pinky promise clipart 3 » Clipart Station
function myPromise(str){
return new Promise((resolve, reject) => {
if (str === 'Yes'){
resolve('Our Promise was resolved')
} else {
reject('Our Promise was rejected')
}
})
}
console.log(myPromise('Yes'))
// logs: Promise {<fulfilled>: "Our Promise was resolved"}
console.log(myPromise('Not Yes'))
// logs: Promise {<rejected>: "Our Promise was rejected"}
function myPromise(str){
return new Promise((resolve, reject) => {
function checkString(){
if (str === 'Yes'){
resolve('Our Promise was resolved')
} else {
reject('Our Promise was rejected')
}
}
setTimeout(checkString, 10000)
})
}
console.log(myPromise('Yes'))
//logs : Promise {<pending>}
console.log(myPromise('Not Yes'))
//logs : Promise {<pending>}
//10 seconds later logs: Uncaught (in promise) Our Promise was rejected
myPromise('Yes')
.then(resp => console.log(resp))
myPromise('Not Yes')
.catch(resp => console.log(resp))
// 10 seconds pass...
//logs: Our Promise was resolved
//logs: Our Promise was not resolved
Promise.all([fetch(url1), fetch(url2)])
.then(([resp1, resp2]) => {
return Promise.all([resp1.json(), resp2.json()])
})
.then(([data1, data2]) => {
doSomething(data1)
doAnotherThing(data2)
});

--

--

Current Web Development student at https://flatironschool.com/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store