Skip to content

Instantly share code, notes, and snippets.

@Ebazhanov
Last active May 18, 2020 12:06
Show Gist options
  • Save Ebazhanov/6fd788af26db094126023dd0a0d20ce2 to your computer and use it in GitHub Desktop.
Save Ebazhanov/6fd788af26db094126023dd0a0d20ce2 to your computer and use it in GitHub Desktop.
One of the example how to use promise (with async code) in javascript
=========WITHOUT PROMISE====================
console.log('Request data...')
setTimeout(() => {
console.log('Preparing data...')
const backendData = {
server: 'aws',
port: 2000,
status: 'working'
}
setTimeput(() => {
backendData.modified = true
console.log('Data received', backendData)
}, 2000)
}, 2000)
=========WITH PROMISE====================
const promise = new Promise(function(resolve, reject) {
setTimeout(() => {
console.log('Preparing data...')
const backendData = {
server: 'aws',
port: 2000,
status: 'working'
}
resolve()
},2000)
})
promise.then(data => {
return new Promise((resolve, reject) => {
setTimeout(() => {
data.midfied = true
resolve(data) //reject(data)
}, 2000}
})
// promiseSecond.then(clientData => {
// console.log('Data received', clientData)
// })
})
===========how to handle errors============
.then(clienData => {
clientData.fromPromise = true
return cleintData
})
.then(data => {
console.log('Modified', data)
})
.catch(err => console.error('Error:', err))
============FINALLY always exectued===========
.finally(() => console.log('Finally'))
=========SLEEP===============
const sleep(() => {
return new Promise (resolve => {
setTimeput(() => resolve(), ms)
})
}
// sleep(2000).then(() => console.log('After 2 sec'))
// sleep(3000).then(() => console.log('After 3 sec'))
=============WAIT for several methods====================
Promise.all([sleep(2000), sleep(5000)]).then(() => {
console.log('All promises')
})
=============TO SEE what was executed first===========
Promise.race([sleep(2000), sleep(5000)]).then(() => {
console.log('All promises')
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment