三句话总结 async await 用法

公司有个项目,相似用户自定义试卷的功能,不少表单须要验证,可是又要根据配置自动生成,因此,每一个输入框都是一个组件,验证是异步,若是所有都用Promise看起来也很头大,各方查阅,总结以下。异步

三句话看懂 async/await

1 async 函数执行结果都是Promise

clipboard.png

async function HiAsync() {
 return "hi";
}
async function HelloAsync() {
 return Promise.resolve('hello')
}

console.log(HiAsync())
console.log(HelloAsync())

HiAsync().then(r => {
    console.log(r) // 'hi'
})
HelloAsync().then(r => {
    console.log(r)  // 'hello'
})

2 await 总能等到结果

(即使是嵌套多层的异步)async

clipboard.png

function getSomething() {
    return "a";
}

async function testAsync() {
    return new Promise((re, rj) => {
        setTimeout(() => { re('b') }, 500)
    })
}
async function deepAsync() {
    let p2 = new Promise((re, rj) => {
        setTimeout(() => { re('c') }, 10)
    })
    return new Promise((re, rj) => {
        setTimeout(() => { re(p2) }, 500)
    })
}

async function test() {
    const v1 = await getSomething();
    console.log('v1',v1)
    const v2 = await testAsync();
    console.log('v2',v2)
    const v3 = await deepAsync();
    console.log('v3',v3);
}
test();

3 await 的使用时 必须在async 函数中

easy? 表述可还清楚?有遗漏请指正。函数

相关文章
相关标签/搜索