最後一篇技術文囉!想了很久最後一篇要寫什麼,本來想寫正規表達式或探究this,最後選擇async await,雖然有點超出我目前學習範圍,但由於前幾天再研究非同步,想一氣呵成,不想要結束在半路上迷路的感覺。
async function getPromise() {
return 'hello'
}
const dataPromise = getPromise()
console.log(dataPromise);
const p = new Promise( function (resolve, reject) {
resolve('promise resolved value!')
})
async function getPromise() {
return p
}
p.then(res => console.log(res))
//promise resolved value!
const p = new Promise( function (resolve, reject) {
resolve('promise resolved value!')
})
function getPromise() {
p.then(res => console.log(res))
}
getPromise()
async await handling
await function name(params) {
//more coding...
}
const p = new Promise( function (resolve, reject) {
resolve('promise resolved value!')
})
async function handlePromise() {
const val = await p
console.log(val);
}
handlePromise()
console.log('hello')
const p = new Promise( function (resolve, reject) {
setTimeout(() => {resolve('promise resolved value!')}, 10000)
})
function getPromise() {
p.then(res => console.log(res))
console.log('hello');
}
getPromise()
印出順序會是先'hello',10秒後再印出'promise resolved value!'console.log('hello')
const p = new Promise( function (resolve, reject) {
etTimeout(() => {resolve('promise resolved value!')}, 10000)
})
async function handlePromise() {
const val = await p
console.log('hello');
console.log(val);
}
handlePromise()
會在10秒後先印出hello再印出promise resolved
const p1 = new Promise( function (resolve, reject) {
setTimeout(() => {resolve('hello, my friend.')}, 5000)
})
const p2 = new Promise(function (resolve, reject) {
setTimeout(() => { resolve('how are you?') }, 10000)
})
async function handlePromise() {
const val1 = await p1
console.log(val1);
const val2 = await p2
console.log(val2);
}
handlePromise()
會依序在5秒後印出'hello, my friend.'10秒後印出'how are you?'
const p1 = new Promise( function (resolve, reject) {
setTimeout(() => {resolve('hello, my friend.')}, 10000)
})
const p2 = new Promise(function (resolve, reject) {
setTimeout(() => { resolve('how are you?') }, 5000)
})
async function handlePromise() {
const val1 = await p1
console.log(val1);
const val2 = await p2
console.log(val2);
}
handlePromise()
會在10秒後依序印出'hello, my friend.'跟'how are you?'
在比較一般的promise handling跟async await時,覺得對於印出順序的差異感到很驚訝也很有趣,期待我很快的會用上它,感受它的美好。
努力看完天書後,來點輕鬆的吧!分享我兒子的童言童語,調劑身心一下
2020/12/11
昨晚在跟樂咖碎唸他沒說到做到,
我:你說你不會再吃餅乾,事實上你又吃了!
咖:餅乾不是40,是90!
ㄜ不知道該怎麼接下去⋯
2020/11/24
阿咖的感冒終於告一段落,
昨晚用之前部門聚餐我主管給他的哈根達斯券換了冰淇淋回家吃,一口也不分我⋯
我:為什麼我老闆只給你沒給我?
阿咖:媽咪,你明天去跟你老闆說你感冒好了!