對比傳統回調函數與Pormise的寫法javascript
// 聲明函數 function run(callback) { let parmas = 0; if (callback) callback(parmas); }; function fnStep1(callback) { let parmas = 123; if (callback) callback(parmas); }; function fnStep2(callback) { let parmas = 456; if (callback) callback(parmas); }; function fnStep3(callback) { let parmas = 789; if (callback) callback(parmas); }; // fnStep4 ... // 傳統使用回調的寫法 run(function (parmas) { // parmas = 0 console.log(parmas); fnStep1(function (parmas1) { // parmas = 123 console.log(parmas1); fnStep2(function (parmas2) { // parmas = 456 console.log(parmas2); fnStep3(function (parmas3) { // ... // 一直嵌套 }); }); }); });
let p = new Promise((resolve, reject) => { // ?異步操做,最終調用: // const parmas = 0; resolve(parmas); // fulfilled // ?或 // reject("failure reason"); // rejected }) p .then( (parmas) => { // parmas,resolve返回的值 console.log(parmas); // 你的代碼塊 code... return 123; //返回值給下一個then } ) .then( (parmas) => { // parmas,上一個then返回的值 console.log(parmas); // 你的代碼塊 code... return 456; //返回值給下一個then } ) .then( (parmas) => { // parmas,上一個then返回的值 console.log(parmas); // 你的代碼塊 code... return 789; //返回值給下一個then } )
Promise要比傳統回調函數更簡潔直觀,可讀性更強。java
那如何使用Promise進行異步回調? 如何捕獲錯誤?promise
// 聲明函數 function asyncFn(a) { return new Promise((resolve, reject) => { a += 1; setTimeout(function () { // 使用resolve則返回a resolve(a); // 使用reject則返回錯誤,並結束then的繼續向下執行,並會跳到catch // reject(new Error("fail")); }, 2000); }); } // 執行 asyncFn(1).then( (a) => { // 過了2秒後接收到a值 => 2 console.log(a); const newVal = 5; // const newVal = {a: 5}; // const newVal = new Promise((resolve, reject) =>{}); // 返回值能夠是數字,字串,對象或者是 Promise return newVal; } ).then( (newVal) => { // newVal 得到上一個then返回的值 或 返回的Promise的返回值 } ).catch( (err)=>{ // 如用到reject,則會直接跳到此處 console.log(err) } );