Skip to content

Instantly share code, notes, and snippets.

@taichunmin
Last active November 7, 2017 07:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save taichunmin/ef17f19c5905ff5562f4d56cf837fdee to your computer and use it in GitHub Desktop.
Save taichunmin/ef17f19c5905ff5562f4d56cf837fdee to your computer and use it in GitHub Desktop.
// 一般的寫法
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