Javascript Engine is synchronous
- The core javascript V8 engine for example is synchronous
- Nodejs and Browser adds the asynchronous functionality
JavaScript Asynchronous Programming
- JS is single threaded, hence there is browser thread, but still there is a mechanism to run code asynchronously.
Example Async functions in JS (Browser)
- XMLHttpRequest methods
- Timing methods:
setTimeout() - Animation methods:
requestAnimationFrame() fetch()
Callbacks
- A function passed to some other function, which we assume will be invoked at some point
- The function “call backs” invoking the function you give it when it is done doing its work.
// signature
setTimeout(callback, delay);
// example
console.log("Hi!");
setTimeout(function() {
console.log("Asynchronous Result");
}, 5000);
console.log("Synchronous Result");- Here we have used an
anonymousfunction in the callback - Callbacks can also be used synchronously but it is useful in async code
Error-First Callback
- callback takes error object as the first parameter
const callback = function(err, data) {
// call back body
}Promises
promise
.then(function(result) {
// do something with result
return(newResult)
})
.catch(function(error) {
// deal with error
})
.finally(function() {
// runs after promise is fulfilled or rejected
});Async-Await
asyncandawaitare just syntactical sugar on promises- code with async-await can be transpiled to Promises using Babel
asyncbefore a function mean that the function will always return a promise- function does not become a promise itself
async function f() {
return 1; // returns a value, will be wrapped in promise
}
async function f2() {
return Promise.resolve(2); // returns a promise
}
f().then(res => console.log(res)); // 1
f2().then(res => console.log(res)); // 2More Examples of Async Functionality in Browser
Web Worker
It enables you to write code that will be executed in its own thread on the processor separate from the browser thread.
Service Worker
- A service worker runs in a separate thread
- Like Web Worker It can run the code and send the response back
- Optimized to make network requests, monitor responses, and work with those reponses all in background
WebSockets
- It maintains a persistent connection to the server and listens for updates
AJAX, XMLHTTPRequest, fetch
- AJAX is a buzzword meaning “Making an HTTP request from JavaScript without leaving the page”.
- AJAX stands for Asynchronous JavaScript and XML
- With Ajax, web applications can send and retrieve data from a server asynchronously (in the background) without interfering with the display and behaviour of the existing page.
- These days JSON is preferred instead of XML
- AJAX can be accomplished by:
- XMLHttpRequest
- fetch: more modern and built around promises
- REST is an architecture style for sending and handling HTTP requests. So you can use AJAX to send RESTful requests. A REST API can be accessed by an AJAX client.
- Ref: