Async, await, promises & callbacks in JavaScript

Promises : Courtesy to this medium article Promises in javascript are very similar to promises made in real life. They can be kept & b...

Promises : Courtesy to this medium article

Promises in javascript are very similar to promises made in real life. They can be kept & broken. If its kept we react differently & also when its not kept we react differently.

 

Promises has two parts :

1) Creating Promise

2) Handling Promise

 

Simple Example

let promise = new Promise(function(resolve, reject) 
{
if(promise_kept)
resolve("done");
else
reject(new Error("…"));
});

 

As it can be seen, Promises don’t return values immediately. It waits for the success or failure and then returns accordingly. This lets asynchronous methods return values like synchronous ones. Instead of returning values right away, async methods supply a promise to return the value.

 

Chaining Promises

A promise can be returned to another promise , creating a chain of promises. If one fails all others too. 

new Promise(function(resolve, reject) {

setTimeout(() => resolve(1), 1000);

}).then(function(result) {

alert(result);
return result * 3;

}).then(function(result) {

alert(result);
return result * 4;

}).then(function(result) {

alert(result);
return result * 6;

});

 

All of the operations return there results to the next then() function on resolve and this process continues till the chain is complete. The last element in the chain return the final result.

 

Async & Await : Courtesy to this medium article 

What is Async & Await?

Async and Await are extensions of promises. Async functions enable us to write promise based code as if it were synchronous, but without blocking the execution thread.

 

async function firstAsync() {
return 27;
}

firstAsync().then(alert); // 27

 

Running the above code gives the alert output as 27, it means that a promise was returned, otherwise the .then() method simply would not be possible.

 

Await : The await operator is used to wait for a Promise. It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution.

 

The code block below shows the use of Async Await together.

 

async function firstAsync() {
let promise = new Promise((res, rej) => {
setTimeout(() => res("Now it's done!"), 1000)
});

// wait until the promise returns us a value
let result = await promise;

// "Now it's done!"
alert(result);
}
};
firstAsync();

 

Important Node : We cannot use await inside normal function. The function must have async keyword if you want to use await.


Async & Await makes execution sequential. The below takes 100ms to complete :

async function sequence() {
await promise1(50); // Wait 50ms…
await promise2(50); // …then wait another 50ms.
return "done!";
}

 

Another way of working with more then one promises :

async function sequence() {
await Promise.all([promise1(), promise2()]);
return "done!";
}

 

The promise.all() function resolves when all the promises inside the iterable have been resolved and then returns the result.

 

Last Method :

async function parallel() {    // Start a 500ms timer asynchronously…
const wait1 = promise1(50); // …meaning this timer happens in parallel.
const wait2 = promise2(50);

// Wait 50ms for the first timer…
await wait1;

// …by which time this timer has already finished.
await wait2;

return "done!";
}

 

Now in this part of article we will see why do we even need Async & Await. Lastly we will build simple web app based on the concept we have learned so far.


Courtesy of this section goes to them

 

We need promises because nesting callbacks will soon look like :

 


When callbacks are nested in this way it becomes difficult to understand & debug the code. So here basically callbacks come in action.


Difference between Promises & Async / Await can be understood by below code :

// Async/Await
const asyncGreeting = async () => 'Greetings';

// Promises
const promiseGreeting = () => new Promise(((resolve) => {
resolve('Greetings');
}));

asyncGreeting().then(result => console.log(result));
promiseGreeting().then(result => console.log(result));

 

Now finally if you want to apply this knowledge practically then make sure to follow along with this article where you will learn how to create basic currency converter using Async / Await.

COMMENTS

Nama

2fa,2,adsense,3,ai,28,Alat,1,Algorithms,3,Android,29,anti virus,1,Apache,4,api,4,apipedia,2,Aplikasi Android,10,apps,2,AppSheet,40,arang,1,Array,3,array formula,2,Artikel,8,bca,1,Belajar,1,Bengkak,1,Berita,1,Berita terkini,12,Biografi,1,Bisnis,139,Bitcoin,1,Blog,7,Blogger,34,Blogger Template,1,Blogging,2,Bootable,1,bot,1,build with syahdandev,13,bun.js,1,catlang,1,chat gpt,1,Cheat,1,Chrome,2,Code,14,coding,11,collaboration tools,1,Competitive Coding,7,CPU,1,Crud,1,CSS3,2,cybersecurity,2,Data Structures,18,Database,1,Deep Learning,3,Desain Blogger,47,Design,3,developer,5,Development,8,Domain Hosting,2,Download,4,dunia kerja,2,Elon Musk,4,enak,1,excel,1,express,1,Facebook,2,fact or hoax,1,fastify,1,free,1,Free Course,13,Game,5,Gamers,2,gemini,1,generate with AI,2,generator,1,github,1,google,12,Google AdSense,20,Google Apps Script,23,google calendar,1,google docs,2,google drive,2,google forms,1,google mail,1,google maps,1,Google Script,3,google sheets,10,Google Webmaster Tools,1,Hardware,1,Home,1,hosting,4,Hostinger,1,HP,2,HTML,6,HTML5,2,HyperOs,1,ice cream,1,ide kreatif,2,image creator,2,Indonesia,1,Instagram,2,instant vdeo generator,1,integrator,1,Internet,8,iOS,1,IOT,2,iphone,1,IT,6,JavaScript,6,js,4,Kenali,1,Keren,1,Kesehatan,14,laragon,1,laravel,1,Leet Code,7,library,1,Linked List,4,Linux,8,Machine Learning,4,malware,1,map,1,Mark Zuck,1,Marketing Tools,1,marketplace,1,Mata,1,Math,8,mbti,2,McDonald's,1,meme,1,meta,1,mfa,1,Microsoft Word,1,Minimalis,1,miscellaneous questions,1,mixue,1,Mobile Legends,4,Motherboard,1,motivasi,1,murah,1,mysql,5,Neovim,1,Networking,1,next js,1,ngingx,1,NIK,1,NLP,1,no code,5,node js,9,nodejs,1,NPWP,1,Office,1,open ai,1,Oppo,1,Parallel Space,1,pc,2,PDF Print,1,pgsql,2,Phoenix OS,1,PHP,16,phpmyadmin,2,portofolio,1,postman,3,Power Point,1,Presentation,1,price list,1,Program Aplikasi,6,programmer,3,programming,1,psikolog,4,python,4,query,1,Quesions or Answers (Quora),2,Questions or Answers (Quora),1,RAR,2,Recursion,3,regex,2,Regulasi,1,Review,147,Rufus,1,Rumus,55,Sakit,1,Samsung,1,Security,1,SEO,21,SHAREit,1,shop,1,simple apps,2,Smart City,1,smartfren,1,Smartphone,1,sms,1,Social Media,1,socket.io,2,Software,2,spesifikasi,1,SQL,1,SQL Server,1,Steemit,7,string,3,team IT,1,Tebak Gambar,2,Technology,4,Teknologi,8,Teknologi Informasi,3,Telegram,3,Template Blog SEO,10,Template Blogger,1,Templates,1,terminal,1,tiktok,1,Tips,22,Tips & Trik,19,Tips Blogging,36,Tips SEO,23,toolkit,1,Tree,8,Trick,27,trik,3,Tulisan Lepas,1,tutorial,6,Tutorial CSS,3,Tutorial HTML,56,Tutorial JavaScript,3,Twitter,2,Ubuntu,5,udemy,7,UX,8,VirtualBox,1,VLC Media Player,1,VSCode,2,waconsole,19,wallpaper engine,1,web dev,2,Web Server,5,WhatsApp,14,WhatsApp Gateway,8,Widget,2,Windows,25,wordpress,4,XAMPP,7,Xiaomi,5,Yii2,1,YouTube,3,
ltr
item
Syahdan Dev Blog: Async, await, promises & callbacks in JavaScript
Async, await, promises & callbacks in JavaScript
https://miro.medium.com/max/1132/1*2Nco5zYP_Xv-5-FgL6kCuw.png
Syahdan Dev Blog
https://syahdandev.blogspot.com/2020/09/async-await-promises-callbacks-in.html
https://syahdandev.blogspot.com/
https://syahdandev.blogspot.com/
https://syahdandev.blogspot.com/2020/09/async-await-promises-callbacks-in.html
true
6341435550051226882
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content