Open benson00077 opened 3 years ago
整理一下,也接續問一下。
當我把 Test 修正為傳遞 cb 而不是呼叫之後
test1(options, () => console.log("This sentence show at the end"))
// "data fetching..." → "This sentence show at the end" → "Execute after 0.3 sec"
test2(options, () => console.log("This sentence show at the end"));
// "data fetching..." → "Execute after 0.3 sec" → "This sentence show at the end"
test3(options, () => console.log("This sentence show at the end"));
// "data fetching..." → "Execute after 0.3 sec" → "This sentence show at the end"
到這裡我就不懂為何 myAsync1, myAsync3 會不一樣了。讀了一次 await 官方文件 後,我可不可以說:
await asyncExecutor()
,是因為當 async 函式被呼叫時,它會回傳一個 Promise ,所以有 block / pending 的過程
async function myAsync2(options = {}, cb) {
const executer = async () => {
if (options.two) await fakeFetch()
}
if (options.one) executer()
if (typeof cb === "function") cb()
}
test2(options, () => console.log("This sentence show at the end"));
// "data fetching..." → "This sentence show at the end" → "Execute after 0.3 sec"
感謝你第二點的補充,有讓我稍微懂了些。
const fakeFetch = () => {
return new Promise((res, rej)=> {
console.log("data fetching...")
setTimeout(() => {
rej("Message after 0.3 sec") // reject
}, 300)
})
}
補充 Generator , 跟 Promise & async await 關聯,也與協程概念關聯。
Generator 內的關鍵字 yield
,查了一下字典,這個字也有停車讓道、讓出放棄的意思,
像是 Generator 函數把執行所有權讓給別人先執行一樣,蠻有趣的。
參考:JavaScript中的协程
背景解釋
我想模仿 axios 寫一個 promise-based 的函數,如下
且想在呼叫時利用
async
關鍵字,並避免try ... catch
chain,因此有個 HOF 如下利用
async
關鍵字呼叫後,呼叫一個 call back,三種 test case 範例如下 (cb for callback function)最後是在別的檔案中呼叫這三個 test case ,如下
問題
fakeFetch()
有問題嗎?fakeFetch()
要怎麼改才好?fakeFetch()
寫好後比較好釐清這個問題 (先解決1.2問題後我再發問這點)。