r/learnjavascript • • Oct 18 '26

Promises

Understanding the concepts like functions, objects, arrays etc has been easy so far but promises are making my head hurt. Is it supposed to be this confusing? Did u guys struggle with it too when u were first learning it.

10 Upvotes

25 comments sorted by

View all comments

1

u/regardedMAGAfascist Oct 20 '26 edited Oct 20 '26

Promises are syntactic sugar over top of callbacks. That’s how you should think of them. Ignore errors for now.

Without promises, when a timeout is involved, you generally have to write something like

```
function someTask(doAfter) {
setTimeout(()-> {
var someResult = // actual nested business logic
doAfter(someResult)
})
}
```

When you call someTask here, it calls setTimeout and returns immediately and the stuff in the timeout is called later. You can’t do something like this:

someTask()
doAfter()

It won’t work like you expect. And a lot of times that doAfter function also has a setTimeout in it, and it can need its own callback. You get into nested function hell

```
someTask((someResult) -> {
// nested doAfter
})
```

With promises, you can write that like this:

```
var someResult = await someTask()
// not nested doAfter logic
```

Much simpler. Very limited nesting. That’s their main purpose. They get rid of the need to nest your callbacks within each other. They give you the ability to wait on things like setTimeout or fetch, without passing in callback functions.