DEV Community

Sojin Samuel
Sojin Samuel

Posted on

What are Promises in Javascript ? (Help)

I need to hear the answer from a developer, in a simplified way as he/she can possibly put it.

Top comments (7)

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€ • Edited

It's an I Owe You arrangement in code.

Dev: I want this webpages html, when it loads, do you promise to give it to me?

Promise: yes I promise but I may fall over because I haven't tied my shoelaces, if I do, catch me okay?!

Dev: I'm only human?! What do you take me for, alright I will try

Promise: at least I'm not as bad as callbacks

Dev: hey quit yapping, do you have that data?

Victims online bank: hey come back with my HTML!!

Promise: bleep bloo bleep, resolved πŸ€–

Dev: thanks, let's get on with other work

Sorry that turned dark didn't it!?

Collapse
 
sojinsamuel profile image
Sojin Samuel

Thanks for making me move on, i thought i wouldn't understand this

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

No problem, making up stories is my kind of fun 😊

Collapse
 
pilcrowonpaper profile image
pilcrowOnPaper • Edited

Sometimes, you have to wait for something to finish in JavaScript. Maybe you're waiting for an endpoint to return some kind of data. Well, how should JavaScript handle it? Stop all processes and wait for it? Well, no. So, an asynchronous (async) function can return a promise. It's promising you that it will finish whatever it's doing in some time. You can use await to wait for the promise to be fulfilled, in which case you need to use it inside an async function.

a recently written article I just found

Collapse
 
sojinsamuel profile image
Sojin Samuel

Thanks

Collapse
 
lexlohr profile image
Alex Lohr

JavaScript usually runs one command after another. Sometimes, commands take longer, i.e. HTTP Requests; running them that way will block the whole page. Instead, JavaScript runs these things in a way that calls a function (usually called callback) after the command has finished. However, just calling a function that you receive as an argument leads directly into callback hell:

request1(config, function callback1(data) {
  request(data.secondUrl, function callback2(data) {
    request(data.thirdConfig, function callback3(data) {
      // and so on and so forth
    });
  });
});
Enter fullscreen mode Exit fullscreen mode

As you can clearly see, this code gets ugly fast. Helpfully, JavaScript now has a class called Promise which helps to make this more manageable:

  fetch(config)
    .then((data) => fetch(data.secondUrl))
    .then((data) => fetch(data.thirdConfig))
  // and so on and so forth
Enter fullscreen mode Exit fullscreen mode

This way, the code becomes much more readable and still does not block the page.

Collapse
 
sojinsamuel profile image
Sojin Samuel

Thanks for colaborating, your answers would help me a lot for my reference