要避免回調地獄,您可以使用以下幾種方法:
.then()
和.catch()
方法,您可以更好地組織和處理異步操作的結果。示例:
function asyncOperation1() {
return new Promise((resolve, reject) => {
// 異步操作
resolve('Result 1');
});
}
function asyncOperation2(param) {
return new Promise((resolve, reject) => {
// 異步操作
resolve(`Result 2 with ${param}`);
});
}
asyncOperation1()
.then(result1 => {
console.log(result1);
return asyncOperation2('param');
})
.then(result2 => {
console.log(result2);
})
.catch(error => {
console.error(error);
});
示例:
async function asyncOperation1() {
// 異步操作
return 'Result 1';
}
async function asyncOperation2(param) {
// 異步操作
return `Result 2 with ${param}`;
}
(async () => {
try {
const result1 = await asyncOperation1();
console.log(result1);
const result2 = await asyncOperation2('param');
console.log(result2);
} catch (error) {
console.error(error);
}
})();
示例:
function asyncOperation1() {
return new Promise((resolve, reject) => {
// 異步操作
resolve('Result 1');
});
}
function asyncOperation2(param) {
return new Promise((resolve, reject) => {
// 異步操作
resolve(`Result 2 with ${param}`);
});
}
Promise.all([asyncOperation1(), asyncOperation2('param')])
.then(([result1, result2]) => {
console.log(result1);
console.log(result2);
})
.catch(error => {
console.error(error);
});
通過使用這些方法,您可以更有效地組織和管理JavaScript中的異步代碼,從而避免回調地獄。