Skip to content

Instantly share code, notes, and snippets.

@umezo
Last active October 16, 2018 08:47
Show Gist options
  • Save umezo/fabbebc40e800db2ea2f74b75118455e to your computer and use it in GitHub Desktop.
Save umezo/fabbebc40e800db2ea2f74b75118455e to your computer and use it in GitHub Desktop.
Promiseあれこれ
(function () {
const test = async () => {
await Promise.resolve();
return Promise.reject();
};
test().then(() => console.log("then"), () => console.log("reject"));
})();
(function () {
const test = () => {
return Promise.resolve().then(() => {
return Promise.reject();
});
};
test().then(() => console.log("then"), () => console.log("reject"));
})();
//async宣言しただけでtestはPromiseを返すようになる
(function () {
const test = async () => {};
test().then(() => { console.log("then") });
})();
//rejectするPromiseを返すかthrowすれば、rejectハンドリングできる
(function () {
const test = async () => {
return Promise.reject();
};
test().then(() => console.log("then"), () => console.log("reject"));
})();
(function () {
const test = async () => {
throw undefined;
};
test().then(() => console.log("then"), () => console.log("reject"));
})();
(function () {
const test = async () => Promise.reject()
test().then(() => console.log("then"), () => console.log("reject"));
})();
(function () {
const test = () => {
return Promise.reject();
};
test().then(() => console.log("then"), () => console.log("reject"));
})();
Promise.resolve()
.then(() => Promise.reject("FOO"))
.then(() => console.log(1)) // <- skip
.then(() => console.log(2)) // <- skip
.then(() => console.log(3)) // <- skip
.then(
undefined,
function(e){ // <- handle reject("FOO")
console.log(e);
}
);
Promise.resolve()
.then(() => Promise.reject(new Error("FOO")))
.catch(result => {
console.log(result.constructor.name);
});
Promise.resolve()
.then(() => {
throw new Error("BAR");
})
.catch(result => {
console.log(result.constructor.name);
});
Promise.resolve()
.then(() => Promise.reject("FOO"))
.catch(result => {
console.log(result.constructor.name);
});
Promise.resolve()
.then(() => {
throw "BAR";
})
.catch(result => {
console.log(result.constructor.name);
});
Promise.resolve()
.then(() => Promise.reject("FOO"))
.then(
undefined,
function(e){
console.log(e);
}
);
Promise.resolve()
.then(() => {
throw "BAR";
})
.catch(result => {
console.log(result.constructor.name);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment