Js Promise

  • 92
  • 0
  • Js
  • 2020-04-17

處理非同步async 行為  https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise

descript Promise property

action status

Promise Chaining

then (callback, callback)

Promise all、race

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function test (a) {
    return new Promise( ( resolve, reject ) => { 
        if (a) {
            resolve("Success");    
        } else {
            reject("Error");
        }
    })
}  

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

axios 為 promise的非同步工具,非同步的行為無法確定何時End,所以透過下列的屬性,來做行為完後的動作

  • 擱置(pending):初始狀態,不是 fulfilled 與 rejected。
  • 實現(fulfilled):表示操作成功地完成。
  • 拒絕(rejected):表示操作失敗了 

test 進入時,promise為pending狀態,然判斷a logic
                     成功為fulfilled,走resolve,然至test方法外的then action
                     失敗為rejected,走reject,然至test方法外的catch action
test(null)
    .then((res) => {
        console.log(res);
    })
    .catch((err) => {
        console.log(err);
        })
    .finally(
        不管then或catch的action,最後要處理的事情
    );

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

const a = new Promise( (resolve, reject ) => {});    
console.log(a);    //promiseStatus : pending

const a = new Promise( (resolve, reject ) => {
    resolve('success');
});    
console.log(a);    //promiseStatus : resolve

const a = new Promise( (resolve, reject ) => {
    reject('error');
});    
console.log(a);    //promiseStatus : reject

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Promise Chaining - 在於then、catch、finally下的return new Promise 的話,可在該then、catch、finally外面,在.then or .catch

test('a')
.then(res => {
    return test('b');
}).catch( err => {
})
  .then(res => {
  }).catch( err => {
  });

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

then (res, rej)

test('a')
.then((res) => {
    console.log('res');
    console.log(res);
},(rej) => {
    console.log('rej');
    console.log(rej);
});

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

all( array Promise) : 所有的陣列 then結果都完成後,若陣列中有reject,則進入catch,剩下不會收回

race( array Promise) : 第一個先回來陣列then結果,若陣列中有reject,則進入catch,剩下不會收回