Async/await語法糖實現(Generator)

// generator也是一種迭代器(Iterator) 有next方法,並返回一個對象{value:...,done:...}

function run(generatorFunction) {

// 創造出迭代器,下面就能夠操控迭代器開始迭代了
const iterator = generatorFunction()

(function handleNext(value){

const next = iterator.next(value)
 
if(next.done){
 
return next.value
} else {


return Promise.resolve(next.value)
.then(handleNext,(err)=>Promise.resolve(iterator.throw(err)).then(handleNext))
}
})()

}



run(function *(){
try{
const usersResponse = yield fetch(`${apiUrl}/users`)
console.log(usersResponse)
} catch (err){
console.log(err)
}
})


// 假想async 關鍵字就是執行了這個run函數,async函數裏的內容就是用generator包裹住了,全部的await至關於yeild
相關文章
相關標籤/搜索