Callback(hell)
function fn() {
setTimeout(() => {
console.log('1')
setTimeout(() => {
console.log('2')
setTimeout(() => {
console.log('3')
}, 1000)
}, 1000)
}, 1000)
}
fn()
ES6 Promises
function fn() {
return new Promise((resovle, reject) => {
setTimeout(() => {
console.log(1)
resovle()
}, 1000)
}).then(() => {
return new Promise((resovle, reject) => {
setTimeout(() => {
console.log(2)
resovle()
}, 1000)
})
}).then(() => {
return new Promise((resovle, reject) => {
setTimeout(() => {
console.log(3)
resovle()
})
})
}
fn()
ES8 async/await
async function fn1() {
return new Promise(resolve => {
setTimeout(() => {
console.log('1');
resolve();
}, 1000)
})
}
async function fn2() {
return new Promise((resolve,reject) => {
setTimeout(() => {
console.log('2');
resolve();
}, 1000)
})
}
async function fn3() {
return new Promise(resolve => {
setTimeout(() => {
console.log('3');
resolve();
}, 1000)
})
}
async function fn() {
await fn1()
await fn2()
await fn3()
}
fn()