• javascript异步编程 Async/await


    Async/await

    Async/await 在学习他之前应当补充一定的 promise 知识

    它是一种与 promise 相配合的特殊语法,目前被认为是异步编程的终级解决方案

    值得我们每一个人学习0

    Async

    它的字面意思本身就是异步的简写,在代码中他被放置在函数前面,可以使得函数的返回值 value 转化为一个 promise

    	async function fun(){
        return 123
    	}
    	const res = fun();
    	console.log(res);
    

    image-20191106145703545

    如上图所示,对于非 promise 对象它会通过 Promise.resolve() 方法吧函数的 return 转化为 promise 对象,这种写法,我们便可以通过原始的 .then() 方法来获得返回值

    await

    await 等待,他等待着async 函数的返回值,这不仅仅适用于 Promise 对象,他适合于任何表达式结果,所以他的后面是可以接普通函数调用的直接量的,

    await 如果等待到的是一个不是 Promise 对戏那个,那么 await 表达式的运算结果就是它等到的东西, 如果它等到的是一个 Promise 对象,它会阻塞后面的代码,等着 Promise 对象 resolve,然后得到 resolve 的值,作为 await 表达式的运算结果。 而他之所以被要求写在 Async 函数里面就是因为这样它会在 Promise 中异步执行

    Async/await的优势

    Async/await的优势就在于处理 .then() 的函数链

    在处理多个 Promise 对象时,函数代码辨识度会很高,避免多个.then() 相互嵌套,

    同时 await 命令后面的 Promise 对象,运行结果可能是 rejected ,所以最好把 await 命令放在 try...catch 代码块中。

    //定时的函数三次异步回调
    function fun() {
        const time1 = 300;
        fun1(time1)
            .then(time2 => fun2(time2))
            .then(time3 => fun3(time3))
            .then(result => {
                console.timeEnd("thefun");
            });
    }
    
    async function fun() {
        console.time("fun");
        const time1 = 300;
        const time2 = await fun1(time1);
        const time3 = await fun2(time2);
        const result = await fun3(time3);
        console.timeEnd("thefun");
    }
    
    

    不仅代码简洁,易读性也更好;

    以上为 async/await 的基本用法,学习之前需理解 Promise 欢迎一起学习进步;

  • 相关阅读:
    -webkit-margin-before 及 扩展浏览器前缀、内核
    vue封装分页组件
    vue项目中使用qrcode生成二维码
    git中全局设置用户名、邮箱
    promise.all 解说
    超详细弹性盒子布局
    js对象转数组
    js取整数、取余数的方法
    数组方法大全
    Vue绑定class
  • 原文地址:https://www.cnblogs.com/baiyang2292/p/11819776.html
Copyright © 2020-2023  润新知