Skip to content

Instantly share code, notes, and snippets.

@k-ta-yamada
Created March 7, 2017 04:12
Show Gist options
  • Save k-ta-yamada/0d05e5ebd878e1f883781bb013c8af8f to your computer and use it in GitHub Desktop.
Save k-ta-yamada/0d05e5ebd878e1f883781bb013c8af8f to your computer and use it in GitHub Desktop.
Promise
// 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