美文网首页
ES6基础之async/await及Promise来处理异步方法

ES6基础之async/await及Promise来处理异步方法

作者: jesse28 | 来源:发表于2021-01-26 07:43 被阅读0次

1. Promise来获取异步方法中的数据:

类似于将一个异步方法封装在一个具有回调函数的函数里,Promise实际上充当了这种封装作用。然后通过resolve和reject函数向外输出成功时的数据和失败时的错误信息,以Promise.then((data)=>{})来接收输出的数据,如下图过程:

image

例如下面的代码:

const p = new Promise((resolve, reject)=>{
    setTimeout(function(){
        const name = 'joyitsai';
        resolve(name);
    /*
    如果失败reject输出错误信息
     reject(`error_info`)
    */
    }, 1000);
})
p.then((data)=>{
    console.log(data);
})

2. async/await与Promise:

所谓的Promise,把它想象成一个容器,里面放着一些正在处理的问题,但不管过多长时间,它最终都会把它处理完成的结果(不管是成功还是失败的)输出给你,而且,它允许你通过.then((data)=>{})方法来接收这个结果数据。Promise可以说是为处理异步而生。

(1) 关于async

而所谓的async,它是将一个方法或函数变成异步的,它会将一个普通函数封装成一个Promise,为什么要封装成Promise呢?其实它只是Promise的搬运工,利用了Promise处理异步问题的能力,能让你更好地解决需要异步处理的代码。。下面看一下简单的代码:

/**async/await 与Promise */
async function testAsync(){
    return 'Here is Async';
}
const result = testAsync();
console.log(result);

执行后,你将会看到:

Promise { 'Here is Async' }

既然async实际上是将一个普通函数封装成了Promise,那么来获取async封装的这个异步方法的数据自然可以用Promise的.then()方法,接着上面的代码,你可用result.then((data)=>{})来接收和处理得到的数据。
但是async的作用如果仅仅是这样,那还要它干嘛?async其实是与await结合使用的,目的在于:直接返回异步方法中的数据:

async function run(){
    const data = await testAsync();
    console.log(data)
}
run();

得到的data就是Here is Async

(2) 关于await

  • async用来申明里面包裹的内容可以进行同步的方式执行,await则是进行执行顺序控制,每次执行一个await,程序都会暂停等待await返回值,然后再执行之后的await。
  • await后面调用的函数需要返回一个promise,另外这个函数是一个普通的函数即可,而不是generator。
  • await只能用在async函数之中,用在普通函数中会报错。
  • await命令后面的 Promise 对象,运行结果可能是 rejected,所以最好把 await 命令放在 try...catch 代码块中。
关于await的理解:

await具有阻塞功能,可以理解为:等待await语句执行完成后,后面的程序才会继续。这就意味着,虽然一段包含await语句的异步程序,最终却是按照同步的顺序来执行。
此外,await的阻塞,意味着它不能用在async以外的函数中,因为await会严重影响非async(异步)程序的执行效率,只能用在async函数中。

下面是await将异步变成同步的代码段:

async function test(){
    console.log(2);
    return 'Joyitsai';
}

async function run(){
    console.log(1);
    const data = await test();
    console.log(data);
    console.log(3);
}
run();

打印结果为:

1
2
Joyitsai
3
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
   
</head>
<body>
    <div id="app">
        <div>
            {{courses}}
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        //模拟异步数据的调用
        function getCourse(){
            return new Promise((resolve,reject)=>{
                setTimeout(()=>{
                    resolve(['vue','react1'])
                },1000);
            });
        }


        async function f1(){
            return 'abc'       //第一步理解:这种写法系统会自动包装成promise对象  return newPromise((resolve)=>{resolve('abc')})
        }

        async function testAsync(){
            return "here is async"
        }
        const result = testAsync();
        console.log(result);
        result.then((data)=>{
            console.log('data...'+data)
        });

        //创建vue实例
        const app = new Vue({
            el:'#app',
            data(){
                return{
                    title:'jesse',
                    course:'',
                    courses:[],
                    totalCount:0
                }
            },
            async created(){
               const courses = await  getCourse(); 
               this.courses = courses;
               console.log( this.courses)  //这边打印出来['vue','react1'],相当于上面reslove里面的实参
            },
            methods:{

            }
        });
    </script>
</body>
</html>

promise中then的几种返回值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        let p = new Promise((resolve,reject)=>{
            resolve('123')
        })

        p.then((info)=>{
            console.log(info)
            // return 123;
            return new Promise((resolve,reject)=>{
                reject();
            })
        }).then((msg)=>{
            console.log('成功了',msg)
        },()=>{
            console.log('失败了')
        })   

        // then的返回值 会有几个不同的状态  
        // 1. then 没有返回值 就会默认返回一个promise为resolve的实例 
        // 2. then 有返回值,但它的返回值不是promise 那他会给一个 promise为resolve的实例 并且会将返回值传给下一个then
        // 3. then 返回的是一个自定义promise,它会根据你最终的状态决定走哪个函数

    </script>
</body>
</html>

在promise的reject之后会执行catch,catch执行之后会返回一个成功的promise所以会执行catch之后的then,除非在catch里面显式的返回一个reject之后才会执行catch之后的catch

参考链接:https://blog.csdn.net/qq_15506981/article/details/112638756

image.png
  <script>
        window.onscroll = function () {
            console.log(this)
        }
        new Promise((resolve, reject) => {
            setTimeout(() => {
                reject();
            }, 1000)
        })
            .then(() => {
                console.log("1.成功了")
                throw new Error("第一个then出错")
            }, () => {
                console.log("1.失败了");
                throw new Error("第一个then出错")
            })

            .then(() => {
                console.log("2.成功了")
            }, () => {
                console.log("2.失败了");
                throw new Error("第2个then出错")
            })
            .catch((err) => {
                console.log(err)
            })
            .then(() => {
                console.log("3.成功了")
            }, () => {
                console.log("3.失败了");
                throw new Error("第3个then出错")
            })

    </script>

相关文章

网友评论

      本文标题:ES6基础之async/await及Promise来处理异步方法

      本文链接:https://www.haomeiwen.com/subject/ofgwzktx.html