ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## async/await 同步 ``` async getBooksAndAuthor(authorId){ const bookPromise = bookModel.fetchAll(); const authorPromise = authorModel.fetch(authorId); const book = await bookPromise; const author = await authorPromise; return { author, books:book.filter(book=>book.authorId === authorId), } } ``` ## async/await 异步 执行 fetch 函数 ``` async function mount() { const result = await Promise.all( fetch('a.json'), fetch('b.json'), fetch('c.json') ); render(...result); } ``` ## then 与 await 比较 ``` function a(code){ return new Promise((resolve, reject)=>{ if (code===1){ resolve({code:1111}) }else{ reject({code:-111}) } }) } function b(code){ return new Promise((resolve, reject)=>{ if (code===1){ resolve({code1:code}) }else{ reject({code1:code}) } }) } function c(code){ return code; } //方式一 let code=1 //成功使用 then。第一个失败会被catch 接受 b(code).then(res=>{ return a(res.code1) }).then(res=>{ console.log(res); }).catch(err=>{ console.log(err); }) //方式二:使用await // then 越长,使用 await 越方便 async function f(code) { try { let res = await b(code); return await a(res.code1) } catch (e) { console.log(e); return false } } let code2=1 f(code2).then(res=>{ console.log(res); }); ``