Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 一般的寫法
new Promise(function(resolve, reject) {
setTimeout(function() {
// resolve()
reject(new Error('123'))
}, 1000)
}).then(function() {
console.log('success')
}).catch(function(e) {
console.error(e)
})
// 可以用 resolve 來帶參數
new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('success1')
// reject(new Error('error'))
}, 1000)
}).then(function(arg1) {
console.log('success', arg1)
}).catch(function(e) {
console.error(e)
})
// 多層的 then
new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('{"a":123}')
}, 1000)
})
.then(JSON.parse)
.then(function(data) {
console.log(data)
})
// then 的錯誤處理
new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('{"a":123')
}, 1000)
})
.then(JSON.parse)
.then(function(data) {
console.log(data)
}).catch(function(e) {
console.error(e)
})
// 偷懶寫法
Promise.resolve().then(function() {
setTimeout(function() {
throw new Error('123')
}, 1000)
}).catch(function(e) {
console.error(e)
})
// 第一層的錯誤處理
new Promise(function(resolve, reject) {
setTimeout(function() {
try {
throw new Error('123')
} catch (e) {
reject(e)
}
resolve('{"a":123}')
}, 1000)
})
.then(JSON.parse)
.then(function(data) {
console.log(data)
}).catch(function(e) {
console.error(e)
})
// 函式回傳 Promise
function fn1() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('success1')
// reject(new Error('error'))
}, 1000)
}).then(function(arg1) {
console.log('success', arg1)
}).catch(function(e) {
console.error(e)
})
}
fn1().then(function(){console.log(1)})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment