Skip to content

Express-node-Begin-to-adavanace/Promise-Async-Await

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 Promise vs Async/Await

This project is a simple Express API that demonstrates two different ways to handle asynchronous code when working with Mongoose:

  1. Promise style.then().catch() callbacks
  2. async/await style — cleaner, more readable syntax

Perfect for beginners who want to see both styles side-by-side!


📚 What This Code Does

  • Connects to MongoDB (via Mongoose)
  • Defines a User schema with name and email
  • Exposes API routes to:
    • Create a user
    • Get all users
  • Each action is implemented twice:
    • Promise style (/users/promise)
    • async/await style (/users/async)

✨ Example Endpoints

1. Promise Style

  • Create User → POST /users/promise
  • Get All Users → GET /users/promise
// Example POST body:
{
  "name": "John Doe",
  "email": "[email protected]"
}

**2. Async/Await Style

-Create User → POST /users/async -Get All Users → GET /users/async

// Example POST body:
{
  "name": "Jane Doe",
  "email": "[email protected]"
}

🧠 Understanding Promise vs Async/Await

  • Promise style
User.find()
  .then(users => res.json(users))
  .catch(err => res.status(500).send(err));

-Looks like a chain of .then() and .catch()

  • Can get messy if you have multiple async steps (callback hell but with nicer syntax)

  • Async/Await style

try {
  const users = await User.find();
  res.json(users);
} catch (err) {
  res.status(500).send(err);
}
  • Reads top-to-bottom like normal code
  • Easier to follow for complex logic = Still uses Promises under the hood — await just unwraps them

🎯 Key Takeaways

  • Both styles work the same — it’s all Promises behind the scenes.
  • Promise style is fine for short chains, but can become harder to read.
  • Async/Await makes async code look synchronous and is easier to debug.
  • In production, always wrap async code in try/catch to handle errors.

Output

1 2 3 4 5 6

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published