首页 > 技术文章 > es6语法的 Promise async 和 await是什么意思

shangrao 2020-11-21 16:55 原文

都是处理异步请求的

// 申明一个异步方法
            async function testAsync() {
                return "hello async";
            }
            
            const result = testAsync();
            console.log(result);  // 输出 Promise 对象。async 函数会返回一个 Promise 对象。
            
            testAsync().then(v => {
                console.log(v);    // 输出 hello async。async 函数可以使用 then() 链来处理这个 Promise 对象
            });

实例1

注意执行先后顺序

// 2s 之后返回双倍的值
            function doubleAfter2seconds(num) {
                return new Promise((resolve, reject) => {
                    // 模拟HTTP请求延时2s
                    setTimeout(() => {
                        resolve(2 * num) //一定要加resolve() 。成功则执行的方法,可以传参。
                    }, 2000);
                })
            }
            //async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成
            async function testResult () {
                console.log('内部调用前 2') // 2
                let result = await doubleAfter2seconds(30);
                console.log(result+'4'); //4
                console.log('内部调用后 5') // 5
            }
            console.log('外部调用前 1') // 1
            testResult();
            console.log('外部调用后 3') // 3
            
            // 2s 之后,输出了60.

实例2 

岁两个方法进行异步调用,执行结果结果为先2秒后输出 one ,再2秒后输出two 和onetwo

// 使用实例                    
                async function init () {
                  try {
                      let first = await getOne();
                      let second = await getTwo();    
                      let res = first + second;
                      console.log(res);
                  } catch (error) {
                      console.log(error);
                  }        
                }
                
                function getOne () {
                    
                    return new Promise((resolve, reject) => {
                       
                        setTimeout(() => {
                            console.log("one")
                            resolve("one") 
                        }, 2000);
                    })
                }
                
               function getTwo () {
                   
                    return new Promise((resolve, reject) => {
                        // vue 中axios使用方法 
                        
                        // axios.get('/two', {data:two}).then((res) => {
                        //     if (res.status === 200) {
                        //         resolve(res)
                        //     }
                        // }).catch((err) => {
                        //     reject(err) //错误时调用方法
                        // })
                        setTimeout(() => {
                            console.log("two")
                            resolve("two") 
                        }, 2000);
                    })
                }
            
             init()

 

推荐阅读