首页  >  文章  >  web前端  >  回调、回调地狱、Promise、异步/等待

回调、回调地狱、Promise、异步/等待

WBOY
WBOY原创
2024-08-29 11:05:331044浏览

Callbacks, Callback Hell, Promises, Async/Await

“编程有时感觉就像一部悬疑电影 - 充满了意想不到的曲折。但是,如果您可以使代码像精心设计的场景一样流畅,该怎么办?欢迎来到回调、Promise 和异步/等待的世界!”

1. 回调

回调 是一个函数,您可以将其作为参数传递给另一个函数,然后在该函数完成后执行该函数。可以这样想:您在线订购电影票,并告诉他们在票准备好后向您发送电子邮件(回调函数)。

示例:
想象一下您正在网上订购电影《蜘蛛侠 4》的门票:

function orderTicket(movie, callback) {
    console.log(`Ordering ticket for ${movie}...`);
    // Simulate a delay with setTimeout
    setTimeout(() => {
        console.log('Ticket ordered successfully!');
        callback();  // Notify when the ticket is ready
    }, 2000);
}

function notifyUser() {
    console.log('Your ticket is ready! Enjoy the movie!');
}

orderTicket('Spider-Man 4', notifyUser);

输出:

Ordering ticket for Spider-Man 4...
Ticket ordered successfully!
Your ticket is ready! Enjoy the movie!

这里的notifyUser是订票后调用的回调函数。

2. 回调地狱

回调地狱 当多个回调相互嵌套时就会发生,导致代码难以阅读和维护。它看起来像金字塔或楼梯,很难跟上正在发生的事情。

示例:
现在想象一下您想要做多项事情,比如订票、买爆米花和找到座位,所有这些都按顺序进行:

function orderTicket(movie, callback) {
    console.log(`Ordering ticket for ${movie}...`);
    setTimeout(() => {
        console.log('Ticket ordered successfully!');
        callback();
    }, 2000);
}

function getPopcorn(callback) {
    console.log('Getting popcorn...');
    setTimeout(() => {
        console.log('Popcorn ready!');
        callback();
    }, 1000);
}

function findSeat(callback) {
    console.log('Finding your seat...');
    setTimeout(() => {
        console.log('Seat found!');
        callback();
    }, 1500);
}

orderTicket('Spider-Man 4', function() {
    getPopcorn(function() {
        findSeat(function() {
            console.log('All set! Enjoy the movie!');
        });
    });
});

输出:

Ordering ticket for Spider-Man 4...
Ticket ordered successfully!
Getting popcorn...
Popcorn ready!
Finding your seat...
Seat found!
All set! Enjoy the movie!

这是回调地狱:您可以看到代码如何变得更加嵌套且更难以阅读。

3.承诺

promise 是一个表示异步操作最终完成(或失败)的对象。它允许您编写更清晰的代码并更轻松地处理异步任务,而不会陷入回调地狱。

示例:
让我们使用 Promise
来简化上面的例子

function orderTicket(movie) {
    return new Promise((resolve) => {
        console.log(`Ordering ticket for ${movie}...`);
        setTimeout(() => {
            console.log('Ticket ordered successfully!');
            resolve();
        }, 2000);
    });
}

function getPopcorn() {
    return new Promise((resolve) => {
        console.log('Getting popcorn...');
        setTimeout(() => {
            console.log('Popcorn ready!');
            resolve();
        }, 1000);
    });
}

function findSeat() {
    return new Promise((resolve) => {
        console.log('Finding your seat...');
        setTimeout(() => {
            console.log('Seat found!');
            resolve();
        }, 1500);
    });
}

orderTicket('Spider-Man 4')
    .then(getPopcorn)
    .then(findSeat)
    .then(() => {
        console.log('All set! Enjoy the movie!');
    });

输出:

Ordering ticket for Spider-Man 4...
Ticket ordered successfully!
Getting popcorn...
Popcorn ready!
Finding your seat...
Seat found!
All set! Enjoy the movie!

Promise 通过链接 .then() 方法使代码更易于阅读,避免嵌套问题。

4. 异步/等待

Async/await 是一种现代语法,允许您编写外观和行为类似于同步代码的异步代码。它建立在 Promise 之上,使代码更加清晰、更容易理解。

示例:
让我们使用 async/await 来处理相同的场景

function orderTicket(movie) {
    return new Promise((resolve) => {
        console.log(`Ordering ticket for ${movie}...`);
        setTimeout(() => {
            console.log('Ticket ordered successfully!');
            resolve();
        }, 2000);
    });
}

function getPopcorn() {
    return new Promise((resolve) => {
        console.log('Getting popcorn...');
        setTimeout(() => {
            console.log('Popcorn ready!');
            resolve();
        }, 1000);
    });
}

function findSeat() {
    return new Promise((resolve) => {
        console.log('Finding your seat...');
        setTimeout(() => {
            console.log('Seat found!');
            resolve();
        }, 1500);
    });
}

async function watchMovie() {
    await orderTicket('Spider-Man 4');
    await getPopcorn();
    await findSeat();
    console.log('All set! Enjoy the movie!');
}

watchMovie();

输出:

Ordering ticket for Spider-Man 4...
Ticket ordered successfully!
Getting popcorn...
Popcorn ready!
Finding your seat...
Seat found!
All set! Enjoy the movie!

使用 async/await,代码更加简单,类似于您在现实生活中描述过程的方式。 wait 关键字会暂停执行,直到 Promise 得到解决,从而使操作流程易于遵循。

概括 :

  • 回调:另一个函数完成其工作后执行的函数。
  • 回调地狱:嵌套回调导致代码难以阅读。
  • Promise: 一种更简洁的方式来处理异步任务,避免回调地狱。
  • 异步/等待:基于 Promise 构建的现代、易于阅读的语法,用于处理异步代码。

“通过掌握回调、Promise 和异步/等待,您可以将复杂的代码变成无缝的体验。告别回调地狱,迎接更干净、更高效的 JavaScript。快乐编码!”

以上是回调、回调地狱、Promise、异步/等待的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn