es6-Async函数

萝らか妹 提交于 2020-03-19 13:35:16

定义

async function 用来定义一个返回AsyncFunction对象的异步函数。异步函数是
指通过实践循环异步执行的函数,他会通过一个隐式的Promise返回其结果

var asyFn = async function(){
}
console.log(asyFn())//Promise {<resolved>: undefined}

语法

async function name([param[,param[,....param]]]){statements}

参数

name——函数名称
param——要传递给函数的参数
statements——函数体语句

var asyncFn1 = async function(){
    console.log("1111")
    return "dddd"
//          return new Error("err")
}
asyncFn1().then(function(res){
    console.log(res)
})

返回值

返回Promise对象会运行执行(resolve)异步函数的返回结果,或者运行拒绝(reject)——如果异步函数抛出异常的话

描述

异步函数可以包含await指令,该指令会暂停异步函数的执行,并等待Promise执行,然后继续执行异步函数,并返回结果,记住await关键字只在异步函数内有效。如果你在异步函数外使用它,
会抛出语法错误。注意,当异步函数暂停时,它调用的函数会继续执行(收到异步函数返回的隐式Promise)

async/await的目的是简化使用多个promise时的同步行为,并对一组Promises执行某些操作。正如Promises类似于结构化回调,async/await更像结合了generators和promise

var resolveAfter2Seconds = function(){
    console.log("starting slow promise");
    return new Promise(resolve => {
        setTimeout(function(){
            resolve("slow");
            console.log("slow promise is done")
        },2000)
    })
}
var resolveAfter1Second =function(){
    console.log("starting fast promise");
    return new Promise(resolve => {
        setTimeout(function(){
            resolve("false");
            console.log("fast promise is done")
        },1000)
    })
}
var sequentialStart = async function(){
    console.log("===SEQUENTIAL START===");
    const slow = await resolveAfter2Seconds();
    const fast = await resolveAfter1Second();
    console.log(fast)
}
var concurrentStart = async function(){
    console.log("===CONCURRENT START with await===");
    const slow = resolveAfter1Second();
    const fast = resolveAfter1Second();
    console.log(await slow);
    console.log(await fast)
}

var concurrentPromise = function(){
    console.log("===CONCURRENT START WITH Promise.all===")
    return Promise.all([resolveAfter2Seconds(),resolveAfter1Second()]).then((message) => {
        console.log(message[0])
        console.log(message[1])
    })
}
var parallel = async function(){
    await Promise.all([
        (async() => console.log(await resolveAfter2Seconds()))(),
        (async() => console.log(await resolveAfter1Second()))()
    ])
}

var parallelPromise = function(){
    console.log("===PARALLEL with Promise.then===");
    resolveAfter2Seconds().then((message) => console.log(message));
    resolveAfter1Second().then((message) => console.log(message))
}

sequentialStart();
setTimeout(concurrentStart,4000)
setTimeout(concurrentPromise,7000)
setTimeout(parallel,1000)
setTimeout(parallelPromise,13000)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!