// output "A" after a random time between 0 & 3 seconds
function outputA(){
var randomTime = Math.floor(Math.random() * 3000) + 1;
return new Promise(function(resolve, reject){
setTimeout(function(){
console.log("A");
resolve("outputA() complete");
},randomTime);
});
}
// output "B" after a random time between 0 & 3 seconds
function outputB(){
var randomTime = Math.floor(Math.random() * 3000) + 1;
return new Promise(function(resolve, reject){
setTimeout(function(){
console.log("B");
resolve("outputB() complete");
},randomTime);
});
}
// output "C" after a random time between 0 & 3 seconds
function outputC(){
var randomTime = Math.floor(Math.random() * 3000) + 1;
return new Promise(function(resolve, reject){
setTimeout(function(){
console.log("C");
resolve("outputC() complete");
},randomTime);
});
}
// invoke the functions using then and catch
function ABC_then_catch(){
outputA()
.then(outputB)
.then(outputC)
.then(outputCMsg => console.log(outputCMsg))
.catch(rejectMsg => console.log(rejectMsg));
}
// invoke the functions using async and await
async function ABC_async_await(){
try{
await outputA();
await outputB();
var outputCMsg = await outputC();
console.log(outputCMsg);
}catch(rejectMsg){
console.log(rejectMsg)
}
}
// Uncomment each function to see how it behaves
//ABC_then_catch();
//ABC_async_await();