0

So basically I was learning promises, async and await functionalities. So the code I wrote was to change the background color after each second using setTimeout() and promises. The problem is when I use .then() with curly braces it doesn't work but if you remove it, it works fine. Can somebody explain it.

This does work partially shows the start and end colors i.e., red and violet in this case.

var colorChange = function (colour, delay) {
return new Promise((resolve, reject) => {
    setTimeout(() => {
        document.body.style.backgroundColor = colour;
        resolve();
    }, delay);
})}

colorChange('red', 1000)
.then(() => {
    colorChange('green', 1000)
}).then(() => {
    colorChange('blue', 1000)
}).then(() => {
    colorChange('yellow', 1000)
}).then(() => {
    colorChange('violet', 1000)
})

And this works all colors after one second each.

var colorChange = function (colour, delay) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            document.body.style.backgroundColor = colour;
            resolve();
        }, delay);
    })
}
colorChange('red', 1000)
    .then(() =>
        colorChange('green', 1000)
    ).then(() =>
        colorChange('blue', 1000)
    ).then(() =>
        colorChange('yellow', 1000)
    ).then(() =>
        colorChange('violet', 1000)
    )

I know this is not a best example of promises and other function but wanted to know what is difference in above and below code. And yes there is no html code other than script linking.

Edit: I understood that promise should return something but why is it working partially in above case if it is not returning.

Amod
  • 11
  • 1
  • `.then` chains are constructed when a `.then` callback returns a Promise. If you don't return anything, there's nothing asynchronous to chain – CertainPerformance May 26 '21 at 04:22
  • so why above code work partially, like it shows red and violet color. – Amod May 26 '21 at 04:29
  • @Amod All of the code in all of the callbacks is running, but there is no wait period after green, blue, and yellow because you are not returning anything from those callbacks. – JLRishe May 26 '21 at 06:54
  • 1
    The second one works, because you don't have curly brackets in your arrow functions. In that case, you return the value returned by the expression (so the promise returned by `colorChange()`. If you _do_ use curly brackets, you need to use `return`, otherwise you are not returning anything at all. See [Curly Brackets in Arrow Functions](https://stackoverflow.com/questions/35440265/curly-brackets-in-arrow-functions) – Ivar May 26 '21 at 08:49
  • Ok I got it . Thanks. – Amod May 27 '21 at 05:08

0 Answers0