天下无坑

天下无坑


Promise、async、await

<h3>声明一个Promise对象</h3> <pre><code>// 常规写法 var p = new Promise(function(resolveFn, rejectFn){ //做一些异步操作 setTimeout(function(){ console.log('执行完成'); resolveFn('随便什么数据'); }, 2000); }); // 箭头函数 var p = new Promise((resolveFn, rejectFn)=&gt;{ //做一些异步操作 setTimeout(function(){ console.log('执行完成'); resolveFn('随便什么数据'); }, 2000); }); // 箭头函数,省略rejectFn var p = new Promise(resolveFn=&gt;{ //做一些异步操作 setTimeout(function(){ console.log('执行完成'); resolveFn('随便什么数据'); }, 2000); }); </code></pre> <h3>多个异步的顺序执行写法</h3> <pre><code class="language-js">function takeLongTime(n) { // 返回一个Promise对象 return new Promise(resolve =&gt; { setTimeout(() =&gt; resolve(n + 200), n); }); } async function doIt() { //time1 阻塞等待一个Promise对象的完成,并接收到resolve的值 const time1 = await takeLongTime(100); console.log(`time1 is ${time1}`); const time2 = await takeLongTime(200); console.log(`time2 is ${time2}`); const time3 = await takeLongTime(300); console.log(`time3 is ${time3}`); return 'done' } doIt().then(returnValue =&gt; { console.log(returnValue) //done }).catch(error =&gt; { console.log(error) }) </code></pre> <h3>多个异步的并列执行写法</h3> <pre><code class="language-js">let wake = (time) =&gt; { return new Promise((resolve, reject) =&gt; { setTimeout(() =&gt; { resolve(`${time / 1000}秒后醒来`) }, time) }) } let p1 = wake(3000) let p2 = wake(2000) Promise.all([p1, p2]).then((result) =&gt; { console.log(result) // [ '3秒后醒来', '2秒后醒来' ] }).catch((error) =&gt; { console.log(error) })</code></pre> <ul> <li> <h4>then()</h4> </li> <li> <h4>catch()</h4> </li> <li> <h4>all()</h4> </li> <li> <h4>race()</h4> </li> </ul>

页面列表

ITEM_HTML