怎么让以下代码避免回调地狱
时间: 2023-07-10 17:32:09 浏览: 51
以下是一个回调地狱的例子,我们可以使用 Promise 或 async/await 来改写它:
```
function doSomething(callback) {
setTimeout(() => {
console.log('First task done');
callback();
}, 1000);
}
function doSomethingElse(callback) {
setTimeout(() => {
console.log('Second task done');
callback();
}, 1000);
}
function doAnotherThing(callback) {
setTimeout(() => {
console.log('Third task done');
callback();
}, 1000);
}
doSomething(() => {
doSomethingElse(() => {
doAnotherThing(() => {
console.log('All tasks done');
});
});
});
```
使用 Promise 的改写方法:
```
function doSomething() {
return new Promise(resolve => {
setTimeout(() => {
console.log('First task done');
resolve();
}, 1000);
});
}
function doSomethingElse() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Second task done');
resolve();
}, 1000);
});
}
function doAnotherThing() {
return new Promise(resolve => {
setTimeout(() => {
console.log('Third task done');
resolve();
}, 1000);
});
}
doSomething()
.then(doSomethingElse)
.then(doAnotherThing)
.then(() => {
console.log('All tasks done');
})
.catch(error => {
console.error(error);
});
```
使用 async/await 的改写方法:
```
async function doTasks() {
try {
await doSomething();
await doSomethingElse();
await doAnotherThing();
console.log('All tasks done');
} catch (error) {
console.error(error);
}
}
doTasks();
```
这样做可以让代码更加清晰易读,避免回调地狱的嵌套。