公司有個項目,相似用戶自定義試卷的功能,不少表單須要驗證,可是又要根據配置自動生成,因此,每一個輸入框都是一個組件,驗證是異步,若是所有都用Promise看起來也很頭大,各方查閱,總結以下。異步
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' })
(即使是嵌套多層的異步)async
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();
easy? 表述可還清楚?有遺漏請指正。函數