Last active
November 7, 2017 07:27
-
-
Save taichunmin/ef17f19c5905ff5562f4d56cf837fdee to your computer and use it in GitHub Desktop.
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
// 一般的寫法 | |
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