// 1. new Promise(fn)
// Creates a Promise instance which doesn't do anything.
// Don't worry, I'll explain this in more detail in a moment.
promise = new Promise(function() {});
// Return a promise which resolves after the specified interval
function delay(interval) {
return new Promise(function(resolve) {
setTimeout(resolve, interval);
});
}
var oneSecondDelay = delay(1000);
//
function animationTimeout(step, interval) {
new Promise(function(resolve, reject) {
if (isAnimationSupported(step)) {
setTimeout(resolve, interval);
} else {
reject('animation not supported');
}
});
}
var firstKeyframe = animationTimeout(1, 1000);
// 2. promise.then(onResolve, onReject)
// Success handler only
promise.then(function(details) {
// handle success
});
// Failure handler only
promise.then(null, function(error) {
// handle failure
});
// Success & failure handlers
promise.then(
function(details) { /* handle success */ },
function(error) { /* handle failure */ }
);
delay(1000)
.then(function() {
console.log('1 second elapsed');
return delay(1000);
})
.then(function() {
console.log('2 seconds elapsed');
});
///=
runAnimation(0);
setTimeout(function() {
runAnimation(1);
setTimeout(function() {
runAnimation(2);
}, 1000);
}, 1000);
//transforms to
runAnimation(0);
delay(1000)
.then(function() {
runAnimation(1);
return delay(1000);
})
.then(function() {
runAnimation(2);
});
// Rejection handlers in promise.then return resolved promises, not rejected ones.
new Promise(function(resolve, reject) {
reject(' :( ');
})
.then(null, function() {
// Handle the rejected promise
return 'some description of :(';
})
.then(
function(data) { console.log('resolved: '+data); },
function(error) { console.error('rejected: '+error); }
);
//result
//resolved: some description of :(
//3. promise.catch(onReject)
try {
runAnimation(0);
}
catch (e) {
runBackup(0);
}
delay(1000)
.then(function() {
runAnimation(1);
return delay(1000);
})
.catch(function() {
runBackup(1);
})
.then(function() {
runAnimation(2);
})
.catch(function() {
runBackup(2);
});
// 4. Promise.all([promise1, promise2, …])
// What does it do?
// It returns a promise which resolves when all of it’s argument promises have resolved, or is rejected when any of it’s argument promises are rejected.
// The returned promise resolves to an array containing the results of every promise, or fails with the error with which the first promise was rejected.
Promise.all([
parallelAnimation1(),
parallelAnimation2()
]).then(function() {
finalAnimation();
});
function finalRequestPromise(options) {
return new Promise(function(resolve, reject) {
finalRequest(options, function(error, data) {
if (error) {
reject(error);
}
else {
resolve(data);
}
});
});
}
// Test your knowledge
Promise
.all([initialRequestA(), initialRequestB()])
.then(function(results) {
var options = getOptionsFromInitialData(results[0], results[1]);
return finalRequestPromise(options);
})
.then(
function(file) { alert(file); },
function(error) { alert('ERROR: '+error); }
);