1. 程式人生 > >Promise中的next 另一個用法

Promise中的next 另一個用法

str 輸出 知識 || ons 銷毀 bind c++ 引用類型

const chainAsync = fns => {
    let curr = 0 ;

    const next = (...args) => fns[curr++](next,...args);

    //執行fns[0](next) : next是一個閉包,包著fns 和 curr ,其中curr只有在next執行的時候才確定fns[curr++]中curr是多少,知識點(函數定義和執行)
    //fns[1](next) : 執行的是fns[0]的next , next()執行時,curr為1
    //fns[2](next) : 執行的時fns[1]的next , next()執行時,curr為2
next();//執行fns[0](next) } //fns :的每個元素[fn1,fn2,fn3,...] //每個元素接受的第一個參數是next,如fn1接受的第一個參數是next函數(...args) => fns[curr++](next,...args) 。由於這時候curr是1 在fn1內執行next就是執行fn2 //同理fn2接收的第一個參數也是next函數(...args) => fns[curr++](next,...args)。由於這時候curr是2 在fn2內執行next就是執行fn3 //後面同理,可見,每次執行next之後,curr才加一,到下一次再執行next的時候,curr是之前的值+1
//這就是閉包的魅力,不但可以緩存curr的值,還可以改變curr的值,到下次再執行時,curr是不同的值 //閉包中緩存的curr是指針?還是基本類型值?還是引用類型? curr是基本類型值,而緩存curr的是一個引用類型 {curr:0} 變量對象 //這裏用了命令模式和閉包 : next是一個命令(宏),lambda,匿名函數,閉包 //命令模式就是一個匿名函數包著一個執行的函數 : 如 (fn)=>fn() //閉包(函數)可以緩存一些變量(類似C++的靜態變量,直到程序結束才銷毀),這裏閉包(函數)緩存的變量就如靜態變量,只有這個閉包(函數)被銷毀這些緩存的變量才被銷毀 // chainAsync([next=>{
// console.log(‘開始‘); // next(‘haha‘);//執行下一個函數fns[1](next,‘haha‘) // },(next,msg) =>{ // console.log(msg); // next();//執行下一個函數fns[2]() // },()=>console.log(‘end‘)]); //class實現 class ChainAsync{ constructor(fns){ this.fns = fns; this.curr = 0; this.next = this.next.bind(this); // this.next = (...args) => this.fns[this.curr++](this.next,...args); //也可以 } next(...args){ this.fns[this.curr++](this.next,...args); } } // const fn1 = (next) => console.log(‘開始‘) || next(‘fn2請接收‘);//執行fn2(next,‘fn2請接收‘) 這裏next就是(next,‘fn2請接收‘)=>fn2(next,‘fn2請接收‘) // const fn2 = (next,msg) =>console.log(msg); //輸出‘fn2請接收‘ // const chain = new ChainAsync([fn1,fn2]); // chain.next(); //輸出: //開始 //fn2請接收

Promise中的next 另一個用法