13. async用法

async

async 是 ES7 才有的与异步操作有关的关键字,和 Promise , Generator 有很大关联的。

语法

async function name([param[, param[, ... param]]]) { statements }
  • name: 函数名称。
  • param: 要传递给函数的参数的名称。
  • statements: 函数体语句。

返回值

async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。

async function helloAsync(){
    return "helloAsync";
  }
  
console.log(helloAsync())  // Promise {<resolved>: "helloAsync"}
 
helloAsync().then(v=>{
   console.log(v);         // helloAsync
})

  

async 函数中可能会有 await 表达式,async 函数执行时,如果遇到 await 就会先暂停执行 ,等到触发的异步操作完成后,恢复 async 函数的执行并返回解析值。

await 关键字仅在 async function 中有效。如果在 async function 函数体外使用 await ,你只会得到一个语法错误。

async function f() {
            // return await 'hello async';
            let s = await 'hello world';
            let data = await s.split('');
            return data;
        }
        // 如果async函数中有多个await 那么then函数会等待所有的await指令 运行完的结果 才去执行
        f().then(v => {
            console.log('v',v)
        }).catch(e => console.log('e',e));

        async function f2() {
            // throw new Error('出错了');
            try {
                await Promise.reject('出错了');
            } catch (error) {

            }
            return await Promise.resolve('hello');
        }
        f2().then(v => console.log('v',v)).catch(e => console.log(e));
原文地址:https://www.cnblogs.com/sunny666/p/12986711.html