Promise
每格一秒顯示,不會一次輸出
function first() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(1)
// 注意resolve的位置
resolve('1 is done')
}, 1000)
})
}
function second() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(2)
resolve('2 is done')
}, 1000)
})
}
function third() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(3)
resolve('3 is done')
}, 1000)
})
}
// execute
first()
.then(res => {
console.log(res)
// 要return後面才接的到資料
return third()
})
.then(res => {
console.log(res)
return second()
})
.then(res => console.log(res))
Async/Await
const asyncRun = async () => {
let three = await third()
let two = await second()
let one = await first()
return `first():${one},second():${two},third():${three}`
}
asyncRun()
.then(res => console.log(res))
.catch(err => console.log(err))
// output
// 3
// 2
// 1
// first():1 is done,second():2 is done,third():3 is done
JQuery Promise
//取得加價價格
function GetAddPrice(Pkey) {
var size = $('#Size_' + Pkey).val()
var color = $('#Color_' + Pkey).val()
// jquery promise
var defer = $.Deferred()
$.ajax({
url: WebRootPath + 'Cart/GetAllSize',
type: 'POST',
data: { Color: color, PKEY: Pkey, Size: size },
dataType: 'JSON',
success: function(data) {
// response resolve's value
defer.resolve(data.AddPrice)
}
})
// 最後需要return promise
return defer.promise()
}
function ChangeSizeEventForCombinationProduct(Pkey) {
var markupPrice = 0
// use $.when().then()
$.when(GetAddPrice(Pkey)).then(function(addPrice) {
//接受傳出的變數
$('#Size_' + Pkey).data('addprice', addPrice)
$.each($('.mSize'), function() {
markupPrice += $(this).data('addprice')
})
$('#originalPrice').text(
currencyIcon + (originalBeforeMarkup + markupPrice).toLocaleString()
)
$('#Price').text(
currencyIcon + (specialPriceBeforeMarkup + markupPrice).toLocaleString()
)
if (markupPrice > 0) $('#AddPricePS').show()
else $('#AddPricePS').hide()
})
}