promise异步请求串行异步then并行异步all竞争异步race 传递参数resolve(then)reject(catch)
生活随笔
收集整理的這篇文章主要介紹了
promise异步请求串行异步then并行异步all竞争异步race 传递参数resolve(then)reject(catch)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.印象
古人云:“君子一諾千金”,這種“承諾將來會執行”的對象在JavaScript中稱為Promise對象。
Promise就是解決多個異步請求的問題
Promise有三種狀態:Pending(進行中)、Resolved(已完成)和 Rejected(已失敗)
串行異步then并行異步all競爭異步race 傳遞參數resolve(then)reject(catch)
2.案例
使用promise執行異步函數我們可以在promise里定義異步函數 ,then與catch分別捕獲resolve與reject拋出的信息
new Promise(function (resolve, reject) {console.log('start new Promise...');var timeOut = 0.5;console.log('set timeout to: ' + timeOut + ' seconds.');setTimeout(function () {if (timeOut < 1) {console.log('call resolve()...');resolve('200 OK INFO');}else {console.log('call reject()...');reject('timeout in ' + timeOut + ' seconds.');}}, timeOut * 1000); }).then(function (r) {console.log('Done: ' + r); }).catch(function (reason) {console.log('Failed: ' + reason); });VM353:2 start new Promise... VM353:4 set timeout to: 0.5 seconds. Promise?{<pending>} VM353:7 call resolve()... VM353:16 Done: 200 OK INFOsetTimeout(function, milliseconds, param1, param2, ...)3.串行執行異步任務:then
<script>function cal(input) {return new Promise(function (resolve, reject) {setTimeout(resolve, 500, "add");console.log(input);});}function add(input) {return new Promise(function (resolve, reject) {setTimeout(resolve, 500, "cal");console.log(input);});}var p = new Promise(function (resolve, reject) {console.log('start');resolve("cal");});p.then(cal).then(add).then(cal);</script><!--start--> <!--3.Promise.html:6 cal--> <!--3.Promise.html:13 add--> <!--3.Promise.html:6 cal-->4.并行執行異步任務:all
var p1 = new Promise(function (resolve, reject) {setTimeout(resolve, 500, 'P1'); }); var p2 = new Promise(function (resolve, reject) {setTimeout(resolve, 600, 'P2'); });// 同時執行p1和p2,并在它們都完成后執行then: Promise.all([p1, p2]).then(function (results) {console.log(results); // 獲得一個Array: ['P1', 'P2'] });5.競爭異步執行任務:race
var p1 = new Promise(function (resolve, reject) {setTimeout(resolve, 500, 'P1'); }); var p2 = new Promise(function (resolve, reject) {setTimeout(resolve, 600, 'P2'); }); Promise.race([p1, p2]).then(function (result) {console.log(result); // 'P1' });由于p1執行較快,Promise的then()將獲得結果'P1'。p2仍在繼續執行,但執行結果將被丟棄。 如果我們組合使用Promise,就可以把很多異步任務以并行和串行的方式組合起來執行。?
?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的promise异步请求串行异步then并行异步all竞争异步race 传递参数resolve(then)reject(catch)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PHP框架的ORM思想:O类的实例化 R
- 下一篇: Git之Sourcetree的commi