Javascript | 分别用async await异步方法和Promise来实现一个简易的求职程序

 
0
关注公众号,一起交流,微信搜一搜: LiOnTalKING

 

JavaScript Promise

Promise 是一个 ECMAScript 6 提供的类,目的是更加优雅地书写复杂的异步任务。
如何创建一个 Promise 对象?
new Promise(function (resolve, reject) {
    // 要做的事情...
});
Promise 的使用:
new Promise(function (resolve, reject) {
    console.log(1111);
    resolve(2222);
}).then(function (value) {
    console.log(value);
    return 3333;
}).then(function (value) {
    console.log(value);
    throw "An error";
}).catch(function (err) {
    console.log(err);
});
执行结果:
1111
2222
3333
An error
 

JavaScript async/await异步方法

  1. async 是“异步”的简写,async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成,await 只能出现在 async 函数中。
  2. async 表示这是一个async函数, await只能用在async函数里面,不能单独使用
  3. async 返回的是一个Promise对象,await就是等待这个promise的返回结果后,再继续执行
  4. await 等待的是一个Promise对象,后面必须跟一个Promise对象,但是不必写then(),直接就可以得到返回值
求职面试
今天要实现的求职面试的程序,总共包含3次面试,上一次面试通过才能进入到下一次面试,3次面试都通过了就算是求职成功了,分别用Promise和async/await两种方式实现对比。
面试方法如下:
//面试
    function interview(round) {
        return new Promise((resole, reject) => {
            setTimeout(() => {
                var score = Math.random();
                if (score > 0.6) {
                    resole(score);
                } else {
                    var err = new Error(`分数:${score}`);
                    err.round = round;
                    reject(err)
                }
            }, 1000);
        });
    };
 
该方法的参数round为第几轮面试,方法返回一个promise,获取一个随机数,随机数就是面试的得分,超过0.6即为通过面试,否则为不通过。
 

通过异步方法来实现求职过程:

//异步方法求职
    async function seekJobs() {
        console.log('seekJobs => start');
        console.time('seekJobs');
        try {
            console.log('第 1 轮面试得分:', await interview(1));
            console.log('第 2 轮面试得分:', await interview(2));
            console.log('第 3 轮面试得分:', await interview(3));
            console.log('yeah!');
        } catch (error) {
            console.error('第 ' + error.round + ' 轮面试没通过:', error);
        }
        console.log('seekJobs => end.');
        console.timeEnd('seekJobs');
        return '求职已经结束。';
    };

通过async声明该方法为异步方法,每一轮面试用await等待返回面试结果,通过可进入下一轮面试,不通过则记录是第几轮面试和得分,最后方法返回信息“求职已经结束。”

通过Promise方式来实现求职过程:

//promise的方式求职
    function seekJobs_P() {
        console.log('seekJobs => start');
        console.time('seekJobs');
        interview(1)
            .then((score) => {
                console.log('第 1 轮面试得分:', score);
                return interview(2);
            })
            .then((score) => {
                console.log('第 2 轮面试得分:', score);
                return interview(3);
            })
            .then((score) => {
                console.log('第 3 轮面试得分:', score);
                console.log('yeah!');
            })
            .catch((error) => {
                console.error('第 ' + error.round + ' 轮面试没通过:', error);
            });
        console.log('seekJobs => end.');
        console.timeEnd('seekJobs');
        return '求职已经结束。';
    };

每一轮面试的通过都会进入到then,打印分数并调用下一轮面试,直到所有面试都通过,中间过程中有一轮面试没通过则进入到catch,最后同样返回信息“求职已经结束“

最后写主程序main方法

/**
     * 主线程
     */
    (function main() {
        console.log('main.start======================================');
        console.time('main');

        //调用求职的异步方法,遇到await不等待,直接返回到mian方法继续执行,main执行完才输出求职返回结果
        // seekJobs().then((res) => {
        //     console.log('求职返回:', res);
        // });

        //调用promise的方式求职,遇到then继续执行并返回"求职已经结束。",回到main方法输出求职返回结果,最后再输出每一次面试的分数
        var res = seekJobs_P();
        console.log('求职返回:', res);

        console.log('main.end======================================');
        console.timeEnd('main');
    })();

 

主程序这里可以分别调用seekJobs和seekJobs_P两种方式的求职。
1、异步方法在遇到await就直接 返回到main方法,main方法继续往下执行,异步方法由另外的线程取执行,执行结束再回调。
2、promise方法则是在遇到then继续执行并返回"求职已经结束。",回到main方法输出求职返回结果,最后再输出每一次面试的分数。
 
posted @ 2022-12-16 22:03  LiOnTalKING  阅读(172)  评论(0编辑  收藏  举报