I wanted to convert callback hell to promises.
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();
So I did this:
let p = new Promise(function (resolve, reject) {
setTimeout(() => {
console.log("order created");
}, 9000)
})
p.then(function () {
setTimeout(() => {
console.log("order received");
}, 2000);
})
.then(function () {
setTimeout(() => {
console.log("preparing food");
}, 3000);
})
.then(function () {
setTimeout(() => {
console.log("order ready");
}, 4000);
})
.then(function () {
setTimeout(() => {
console.log("order delivered");
}, 10000);
})
But my code stops at "order created". Why's it like that? Please help me fix this issue and mainly understand why it is happening and the fix.
But similar code does work.
function createOrder() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('Order created')
resolve()
}, 9000)
})
}
createOrder()
.then(() => {
setTimeout(() => {
console.log('Order received')
}, 3000)
})
.then(() => {
setTimeout(() => {
console.log('Preparing food')
}, 5000)
})
.then(() => {
setTimeout(() => {
console.log('Order Ready')
}, 4000)
})
.then(() => {
setTimeout(() => {
console.log('Order delivered')
}, 6000)
})
I don't understand the reason why my code should not work but the another code can work properly.
Expected output:
order created
order received
preparing food
order ready
order delivered
You need to call resolve
or reject
when using Promise
s. To make this simpler, you can use an async function instead.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
(async()=>{
await sleep(1000);
console.log("order created");
await sleep(1000);
console.log("order received");
await sleep(1000);
console.log("preparing food");
await sleep(1000);
console.log("order ready");
await sleep(1000);
console.log("order delivered");
})();