async await 語法實現

原理promise

async本質上是將串行寫法的promise轉換爲並行(同步)寫法,經過自動執行器,將其轉換爲串行便可實現相同效果
將await替換爲yield,轉換爲generate函數,而後建立其迭代器,經過next,使得函數進入下一步yield
定義自動執行器:判斷next返回的done屬性,爲true時,結束遞歸
不爲true時,遞歸執行執行器根據返回value的類型使用promise.then(... next(res)) 或者 next(value),最終實現並行 轉 串行
複製代碼

實現markdown

async function asyncDetail(){
    	// do something...
    	console.log('aaa');
    	await a();  
    
    	// do something...
    	console.log('bbb');
    	await b();
    
    	// do something...
    	console.log('ccc');
    	await c();
    }
    
    步驟一:
    function* asyncDetailGenerate(){
    	// do something...
    	console.log('aaa');
    	const a = yield test();  
    	console.log('a');
    	
    	// do something...
    	console.log('bbb');
    	const b = yield test();  
    	console.log('b');
    	
    	const d = yield 'dddd';
    	console.log(d);
    	
    	// do something...
    	console.log('ccc');
    	const c = yield test();  
    	console.log('c');
    }
    步驟二:
    const runner = asyncDetailGenerate();
    步驟三:定製執行器
    const autoRunner = (runner,{value,done})=>{
    	if(done){
            return value;
    	}else{
          if(value instanceof Promise){
            value.then(res=>{
                const nextResult = runner.next(res);
                autoRunner(runner,nextResult);
    	    })
          }else{
            const nextResult = runner.next(value);
            autoRunner(runner,nextResult);
          }
    		
    	}
    }
    
    步驟四:autoRunner(runner,runner.next());
複製代碼
相關文章
相關標籤/搜索