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.