Created
March 7, 2017 04:12
-
-
Save k-ta-yamada/0d05e5ebd878e1f883781bb013c8af8f to your computer and use it in GitHub Desktop.
Promise
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
// http://azu.github.io/promises-book/ | |
// https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Promise | |
p = (name, num = 1) => { | |
return new Promise((resolve, reject) => { | |
console.log(`${Date.now()} - num=[${num}] name=[${name}]`); | |
setTimeout(() => { | |
console.log(`${Date.now()} - timeout: num=[${num}] name=[${name}]`) | |
if (name) { | |
resolve("hello " + name + "!"); | |
} | |
else { | |
reject("error"); | |
} | |
}, num * 1000); | |
}); | |
} | |
let foo = p("a") | |
.then(result => { | |
console.log(result); | |
return result; | |
}) | |
.catch(result => { | |
console.log(result); | |
return result; | |
}); | |
setTimeout(_ => { console.log(foo) }, 2 * 1000); | |
Promise.all([ | |
p("b"), | |
p("c", 2), | |
// p(""), | |
]) | |
.then(result => console.log(result)) | |
.catch(result => console.log(result)); | |
Promise.race([ | |
p("a", Math.random() * 10), | |
p("b", Math.random() * 10), | |
p("c", Math.random() * 10), | |
]) | |
.then(result => console.log(result)) | |
.catch(result => console.log(result)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment