JavaScript How to rewrite callback hell using promises as well as async/await?

  • Thread starter Thread starter shivajikobardan
  • Start date Start date
AI Thread Summary
The discussion revolves around converting a JavaScript function that demonstrates callback hell into a more manageable format using promises and async/await. The original function, createOrder, uses nested setTimeout calls to simulate an order process, leading to complex and hard-to-read code. A user attempts to rewrite this using promises but faces confusion regarding proper promise resolution and the structure of async/await. Several participants point out that the initial promise-based attempt does not function correctly due to improper use of setTimeout, which does not return a promise. They emphasize the importance of understanding the concepts behind promises and async/await, rather than just knowing the syntax. Suggestions are made to replace abstract examples with more relatable scenarios to aid understanding. Additionally, a working example using async/await with real API calls is provided to illustrate the concept effectively. Overall, the conversation highlights the challenges of learning asynchronous programming in JavaScript and the need for clear, structured resources.
shivajikobardan
Messages
637
Reaction score
54
TL;DR Summary
callback hell rewriting using promises as well as async/await
JavaScript:
function createOrder() {
  setTimeout(function() {
    console.log("order created");
      setTimeout(function() {
         console.log("order received");
            setTimeout(function() {
               console.log("preparing food");
                  setTimeout(function() {
                      console.log("order ready");
                          setTimeout(function() {
                             console.log("order delivered");
                          }, 6000)
                   }, 4000)
             }, 5000)
      }, 1000)
   }, 2000)
}

createOrder();
This is the callback hell in question.
https://learnwithtriveni.com/2022/08/19/callback-hell-in-javascript/

I want to rewrite it using promises and async awaits.

I've indeed done it with promises and async, as shown here:
JavaScript:
async function createOrder() {
  setTimeout(() => {
    console.log("order created");
  }, 1000)
}

createOrder().then(
  setTimeout(() => {
    console.log("order received");
  }, 2000))

  .then(
    setTimeout(() => {
      console.log("preparing food");

    }, 3000)
  )

  .then(

    setTimeout(() => {
      console.log("order ready");
    }, 4000)
  )

  .then(
    setTimeout(() => {
      console.log("order delivered");

    }, 5000)
  )
Now, I want to do the same using async and await and only using promises.
I know the full syntax of async/await and promises as well.
I'll share if required.

Can you share the code for it? I'm really confused. It'd be really helpful to see and feel the code.

https://www.freecodecamp.org/news/h...llbacks-and-avoid-callback-hell-1bc8dc4a2012/

I've read this article but since I don't know much about burgers(or maybe this article wasn't a great fit for me anyways), this article was so difficult to read for me and I ended up learning nothing.
 
Technology news on Phys.org
Its a bit unclear for me what you are asking. If you really are failing to grasp the patterns presented in that tutorial because you don't know about burgers, then I suggest you mentally replace burgers with some other dish you do know about, or any other sequence of incremental work. Or, if you get lost at a specific step in the tutorial perhaps you can point to where?

And as always on Physics Forum, the more specific questions you ask the more likely you are to receive relevant answers.
 
shivajikobardan said:
Why do you insist on trying to learn from random, unstructured blog posts?

shivajikobardan said:
I've indeed done it with promises and async, as shown here:
That code does not work - that is not how you resolve a promise. It only appears to work because you set longer and longer timeouts - change the 1000 us in the first timeout to 9000 and you will be eating your snack before you order it!

shivajikobardan said:
I know the full syntax of async/await and promises as well.
Knowing the syntax of something is not the same as understanding how to do something (see above).

shivajikobardan said:
I've read this article but since I don't know much about burgers
Are you trying to make a joke? All you need to know about a burger is that it is a piece of cooked meat (beef) between two pieces of bread (buns) and this is explained in the article.
JavaScript:
//   1. Get beef
//   2. Cook the beef
//   3. Get buns for the burger
//   4. Put the cooked beef between the buns
//   5. Serve the burger (from the callback)
 
@pbuk simply i don't get that blog article at all. but I get random blogs because I learn from them, I read them. It'd be great if you could provide ways to fix the issue rather than only shouting at me.
 
I think that many tutorials confuse the issue by creating artificial delayed callbacks with setTimeout. It is easier to learn with a real example, for instance:
JavaScript:
// To use await inside a function it must be declared as async.
async function run() {
  try {
    // ipify.org will tell you your IP address.
    let response = await fetch('https://api.ipify.org?format=json');
    // We have to wait for a response before we can extract the IP address.
    const { ip } = await response.json();

    // Now use the ipinfo.io API to look up information about your IP address.
    response = await fetch(`https://ipinfo.io/${ip}/geo`);
    // Again you have to wait for it before you can do anything with it.
    const info = await response.json();
    console.log(info);
    // Let's return the IP address info so a caller can use it.
    return info;
  } catch (err) {
    console.error(err);
  }
};
 
  • Like
Likes shivajikobardan
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...

Similar threads

Replies
9
Views
1K
Back
Top