less than 1 minute read

Tags: , ,

Promise

  • ES6 實現鍊式調用

  • promise 規範

    • Promise/A
    • Promise/B
    • Promise/C
    • Promise/A+
    • ES6: Promise/A+ 訂定的標準

建立一個 Promise

new promsie(resolve, reject) => {
    if () {

    } else {

    }
}
  • 三種狀態

    • pending
    • fulfilled
    • rejected
      const promise1 = new Promise(function(resolve, reject) {
      resolve('Success!');
      });
        
      promise1.then(function(value) {
        console.log(value);
        // expected output: "Success!"
      });
    
      p.then(onFulfilled[, onRejected]);
     
      p.then(value => {
        // fulfillment
      }, reason => {
        // rejection
      });
    
    • example
     function timer(val, ms) {
        return new Promise((resolve, reject) =>{
           setTimeout(() => {
               console.log(val);
               resolve(val+1)
           }, 1000);
        })
     }
    
     timer(1, 1000).then(val => {
         return timer(val, 1000)
     }).then(val =>{
         return timer(val, 1000)
     })
    
     setTimeOut(()=>{
        console.log('1')  
     },0)
    
     new Promise((res, rej)=>{
        console.log('2');
        res()
     }).then(()=>{
         console.log('3')
     }).then(()=>{
         console.log('4')
     })
    
     console.log('5')
    

Microtask and Macrotask

Imgur

Promise 錯誤處理: catch

new Promise(() => {

}).then()
  .catch()

Promise 的靜態方法

Promise.resolve('Success')
.then(val=> {})

Promse.all(iterable)

Promse.race(iterable)

async/await

  • ES8(ES2017) 引入 promise 的語法糖
async function series() {
    await wait()
}
new Promise((resolve, reject)=>{
   console.log("promise1")
   resolve()
}).then(()=>{
   console.log("then11")
   new Promise((resolve, reject)=>{
      console.log("promise2")
      resolve()
   }).then(()=>{
       console.log("then21")
   }).then(()=>{
       console.log("then23")
   })
}).then(()=>{
    console.log("then12")
})

hackmd.io 簡報好幫手!

  • reveal js