Async History
1. Callback - The past
2. Promise - The present
3. Async/Await - The future
The ppt is from the JavaScript meetup on 15th April 2017 at JSbot, Surat.
2. When you execute something synchronously, you wait for it to
finish before moving on to another task.
When you execute something asynchronously, you can move on
to another task before it finishes.
function Task(){
setTimeout(function () {
console.log("I'm done after 2 seconds")
}, 2000)
console.log("I'll come first");
}
Task()
// I'll come first
// I'm done after 2 seconds
Asynchronous ?
4. If your are dependent on something and It’s
taking time, You’ll be kick off.
function Task(addNum){
var total = Database.query()
// Takes 50ms
var result = total + addNum;
console.log(result);
}
Task(10) // Fires error
Problem
5. If the second task is dependent on the first
task, but the first task taking some time.
Then the second task will not return accurate
output.
var num = 0;
function First(){
setTimeout(function () {
num = 10;
}, 2000)
}
function Second(){
First();
return num % 2; //0
}
Problem
6. Finally
Anything in the code which is taking time will leads to
Asynchronous.
Even if it takes one ms.
8. What to do?
What to do for handle Async tasks?
Implement something
which can gives you the promise
that the dependency
task will get resolved or rejected
properly before dependentTask start.
10. Callback
A callback is a function which will passed as
argument to another function.
A callback function is executed after the current
effect is finished.
$("button").click(function(){
$("p").hide(1000);
alert("The paragraph is now hidden");
});
$("button").click(ImCallback);
function ImCallback(){
console.log("I’ll print after you click");
}
11. Callback looks like
function FastTask(cb) {
setTimeout(function () {
cb(null, 1)
}, 500)
}
function SlowTask(cb) {
setTimeout(function () {
cb(null, 2)
}, 1000)
}
function ErrorTask(cb) {
setTimeout(function () {
cb(new Error('Custom Error'))
}, 1000)
}
function ImCallback(err, result) {
console.log(err, result)
}
FastTask(ImCallback) // 0.5 sec
SlowTask(ImCallback) // 1 sec
ErrorTask(ImCallback) // fire error
Standard Callback has two arguments
1. Error
2. result
callback(err, result)
13. Callback Utility with async
Async is a utility module which provides
straight-forward, powerful functions for
working with asynchronous JavaScript.
npm install --save async
https://caolan.github.io/async/
async.waterfall(
[ GetUser,
GetProfile,
GetAccount,
GetReport,
SendStatistics ], function(){
console.log('done')
})
//parallel
async.parallel([FastTask, SlowTask], function(err, result){
console.log(err, 'done')
})
//series
async.series([FastTask, SlowTask], function(err, result){
console.log(err, 'done')
})
14. Promise
A promise represents the eventual result of an
asynchronous operation. It is a placeholder into
which the successful result value or reason for
failure will materialize.
A promise has 3 states.
Pending: You don’t know the status of the flight.
Resolved: The flight is on time.
Rejected: The flight is canceled due to some
reason.
Promise is accepted as ES6 native API.
Flight
.checkStatus()
.then(function (success) {
console.log('Flight is on time')
},
function (e) {
console.log('Flight is canceled due to ', e.message)
})
.catch(function (e) { //log
console.log('Flight is canceled due to ', e.message)
});
15. Promise Standards
1. Promise is always thenable.
Promise.then()
Flight.checkStatus().then()
2. Promise is chainable.
Promise
.then()
.then()...
.catch()
Flight.checkStatus()
.then(bookFlight)
.catch(handleError)
3. .then has 2 callback arguments
1. resolve & 2. reject
Promise.then(resolve, reject)
Promise.then(
function resolve(result) {
console.log(result)
},
function reject(err) {
console.log(err)
})
# If you don’t want to use reject as second argument, you can
use .catch
Promise.then(
function resolve(result) {
console.log(result)
})
.catch(
function reject(err) {
console.log(err)
})
17. Async & Await
Async/Await introduces in ES7
Async/Await is the next version of Promise.
The new async/await syntax allows you to still
use Promises, but it eliminates the need for
providing a callback to the chained then()
methods.
Async keyword defines an asynchronous
function.
Await indicates that you want to resolve the
Promise.
async function main() {
var users = await request
.get('api.com/users');
console.log('users', users);
}
main();