文章博客

技术团队文档示例


第十三天:async的详细使用

<h4>async</h4> <pre><code>简单实例1: async function fn(){ return 1 } fn.then(alert) 实例2:返回Promise async function fn(){ return Promise.resolve(1) } fn.then(alert) 实例3:等待返回 async function f() { let promise = new Promise((resolve, reject) =&gt; { setTimeout(() =&gt; resolve("done!"), 1000) }); let result = await promise; // 等待promise完成然后返回 alert(result); // "done!" } f(); 实例4:class class Thenable { constructor(num) { this.num = num; } then(resolve, reject) { alert(resolve); // resolve with this.num*2 after 1000ms setTimeout(() =&gt; resolve(this.num * 2), 1000); // (*) } }; async function f() { // waits for 1 second, then result becomes 2 let result = await new Thenable(1); alert(result); //2 } f(); 实例5:与class的调用 class Waiter { async wait() { return await Promise.resolve(1); } } new Waiter() .wait() .then(alert); // 1 实例6:调用函数 async function wait() { await new Promise(resolve =&gt; setTimeout(resolve, 1000)); return 10; } function fn() { // shows 10 after 1 second wait().then( result =&gt; { return console.log(result) ; //10 }); } fn(); //实例7:等待4秒然后返回 async function doubleAndAdd(a,b){ a = await doubleAfter1Sec(a) ; b = await doubleAfter1Sec(b) ; return a + b ; } function doubleAfter1Sec(param){ return new Promise( resolve =&gt; { setTimeout(() =&gt; resolve(param * 2),2000) }) } doubleAndAdd(1,2).then(console.log)</code></pre> <p>链接:<a href="https://blog.csdn.net/u012863664/article/details/78320977">https://blog.csdn.net/u012863664/article/details/78320977</a></p>

页面列表

ITEM_HTML