Last active
November 28, 2023 12:38
-
-
Save pjchender/7e17a190f3facb09dc9cf265db6a3746 to your computer and use it in GitHub Desktop.
Promise and Async/Await Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// async function 本身會回傳 Promise, | |
// 因此 async function 之後也可以用 `.then()` 串起來 | |
main().then(value => { | |
console.log(value); | |
}); | |
async function main () { | |
console.log('start fn') // STEP 1-1 | |
let val = await get() // STEP 1-2 | |
console.log('get value after await', val) // STEP 2-1 | |
let result = await process(val) // STEP 2-2 | |
console.log('result', result) // STEP 3-1 | |
return result; | |
} | |
function get () { | |
console.log('I am in get out of Promise') // STEP 1-3 | |
return new Promise((resolve, reject) => { // STEP 1-4 | |
setTimeout(() => resolve('secret'), 1000) // STEP 1-5 To STEP 2 after 1 sec | |
}) | |
} | |
function process (value) { | |
console.log("I'm in process,", value) // STEP 2-3 | |
return new Promise((resolve, reject) => { // STEP 2-4 | |
setTimeout(() => resolve(`${value}-secret`), 1000) // STEP 2-5 To STEP 3 after 1 sec | |
}) | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Async-Await 搭配 Promise.all 使用 | |
*/ | |
doubleAndAdd(1, 2).then(value => { | |
console.log(`doubleAndAdd(a, b)is ${value}`); | |
}) | |
async function doubleAndAdd(a, b) { | |
const [aAfterDouble, bAfterDouble] = await Promise.all([doubleAfterOneSecond(a), doubleAfterOneSecond(b)]); | |
console.log(`a after double is ${aAfterDouble}. b after double is ${bAfterDouble}`); | |
return aAfterDouble + bAfterDouble; | |
} | |
function doubleAfterOneSecond(params) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => {resolve(params * 2)}, 1000); | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 使用 Async Await 的寫法 | |
**/ | |
getAmountAsync(1); | |
async function getAmountAsync(userId) { | |
try { | |
const user = await getUser(userId); | |
console.log(`User name is: ${user} `); | |
const amount = await getBankBalance(user); | |
console.log(amount); | |
} catch (error) { | |
console.log(error); | |
} | |
} // /使用 Async Await 的寫法 | |
/** | |
* 使用 Promise 的寫法 | |
**/ | |
getAmount(2); // | |
function getAmount(userId) { | |
getUser(userId) | |
.then(getBankBalance) | |
.then(amount => { | |
console.log(amount); | |
}) | |
.catch(error => { | |
console.log(error); | |
}) | |
}// /使用 Promise 的寫法 | |
/** | |
* 呼叫到的其他 function | |
**/ | |
function getUser(userId) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (userId === 1) { | |
resolve('John'); | |
} else { | |
reject('unknown user'); | |
} | |
}, 1000) | |
}) | |
} | |
function getBankBalance(user) { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (user === 'John') { | |
resolve('$ 1,000'); | |
} else { | |
reject('unknown user'); | |
} | |
}, 1000) | |
}) | |
} | |
/** | |
* ================================ | |
**/ | |
/** | |
* Use new Promise directly in .then without putting in callback | |
**/ | |
// EXAMPLE 1 | |
waitASecond(0) | |
.then(waitASecond) | |
.then(waitASecond) | |
.then((second) => { | |
console.log(second) | |
}) | |
function waitASecond(second) { | |
console.log(second) | |
return new Promise((resolve, reject) => { | |
setTimeout(function() { | |
second++ | |
resolve(second) | |
}, 1000) | |
}) | |
} // /EXAMPLE 1 | |
// EXAMPLE2 | |
const calculatePromise = new Promise((resolve, reject) => { | |
console.log('In new Promise, start callback') | |
setTimeout(() => { | |
let answer = 3 + 5 | |
resolve(answer) | |
}, 1000) | |
}) | |
calculatePromise.then(addTwo) | |
.then(addTwo) | |
.then(printResult) | |
function addTwo(value) { | |
console.log('current value', value) | |
return value + 2 | |
} | |
function printResult(value) { | |
console.log('The final value is ' + value) | |
} // // EXAMPLE2 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* EXAMPLE1: 在 Promise 的 callback 中回傳另一個 Promise | |
**/ | |
const returnPromise = new Promise((resolve, reject) => { | |
// 立即執行 | |
console.log('In first Promise, start callback') | |
setTimeout(() => { | |
let data = 10 | |
resolve(data) | |
console.log('In fist Promise, resovle data') | |
}, 1500) | |
}) | |
// 在 Promise 的 Callback 中回傳另一個 Promise | |
.then((value) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(value + 3) | |
console.log('In second Promise, resovle data') | |
}, 1500) | |
}) | |
}) | |
.then((value) => { | |
console.log('In third then, the value is ' + value) | |
}) | |
.catch((reason) => { | |
console.log('Request Failed ' + reason) | |
})// /EXAMPLE 1 | |
/** | |
* EXAMPLE2: 在 Promise 的 callback 中回傳另一個 Promise | |
* 留意這裡的 waitASecond 前面有使用 `return` | |
**/ | |
function waitASecond(seconds) { | |
console.log('start', seconds) | |
return new Promise((resolve, reject) => { | |
setTimeout(function() { | |
seconds++ | |
resolve(seconds) | |
}, 1000) | |
}) | |
} | |
waitASecond(0) | |
.then((seconds) => { | |
console.log('In first .then', seconds) | |
return waitASecond(seconds) | |
}) | |
.then((seconds) => { | |
console.log('In second .then', seconds) | |
return waitASecond(seconds) | |
}) | |
.then((seconds) => { | |
console.log('In third .then', seconds) | |
})// /EXAMPLE 2 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Promise 使用 .then 串接 | |
* 在 .then 裡面 revole(value) 的 value 一樣是 promise 物件, | |
* 可以被傳到下一個 .then 中使用。 | |
**/ | |
const chainPromise = new Promise((resolve, reject) => { | |
console.log('In new Promise, start callback') // 會立即執行 | |
setTimeout(() => { | |
let data = 10 | |
resolve(data) // 1 秒後執行 | |
}, 1000) | |
}) | |
chainPromise.then((value) => { | |
console.log('first .then') // 被 resolve 後執行 | |
return value + 3 | |
}) | |
.then((value) => { | |
// 得到上一個 .then return 的值後執行 | |
console.log('second .then') | |
console.log('The final value is ' + value) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment