Skip to content

Instantly share code, notes, and snippets.

@shiffman
Last active March 28, 2018 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shiffman/7c27c93880dd5633c5fbf0c5f95f205b to your computer and use it in GitHub Desktop.
Save shiffman/7c27c93880dd5633c5fbf0c5f95f205b to your computer and use it in GitHub Desktop.
Working on demonstrating Promises
// Without Promises
setTimeout(function() {
console.log('first thing');
setTimeout(function() {
console.log('then second');
setTimeout(function() {
console.log('and now the third')
}, 1000);
}, 1000)
}, 1000);
// With Promises
delay(1000)
.then(() => {
console.log('first thing');
return delay(1000);
})
.then(() => {
console.log('then second');
return delay(1000);
})
.then(() => {
console.log('and now the third');
return delay(1000);
})
.catch(() => {
console.log('error!')
});
function delay(wait) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), wait);
})
};
// Now an array of Promises
let promises = [];
promises.push(delay(1000));
promises.push(delay(3000));
promises.push(delay(2000));
promises.push(delay(2000));
let allDone = Promise.all(promises);
allDone.then(() => {
console.log('All finished');
})
.catch(() => {
console.log('error!')
});
function delay(wait) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), wait);
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment