Skip to content

Instantly share code, notes, and snippets.

@ichiroku11
Last active February 5, 2018 01:51
Show Gist options
  • Select an option

  • Save ichiroku11/f6603334a0df984c9a1c074d9adaf0b0 to your computer and use it in GitHub Desktop.

Select an option

Save ichiroku11/f6603334a0df984c9a1c074d9adaf0b0 to your computer and use it in GitHub Desktop.
async/awaitとPromiseを試す
// async/awaitとPromiseのサンプル
// Promiseを返す関数
const actionAsync = (result: number) => {
const promise = new Promise<number>((resolve, reject) => {
// 1秒後にresolveする
setTimeout(() => resolve(result), 1000);
});
return promise;
};
// テスト用の関数
const testAcync = async () => {
console.log("await1");
const result1 = await actionAsync(1);
console.log(`result1: ${result1}`);
console.log("await2");
const result2 = await actionAsync(2);
console.log(`result2: ${result2}`);
};
testAcync();
/*
await1
result1: 1
await2
result2: 2
*/
// async/awaitとPromise
// rejectした場合
// Promiseを返す関数
const actionAsync = (result: number) => {
const promise = new Promise<number>((resolve, reject) => {
// 1秒後にresolveまたはrejectする
setTimeout(() => result < 0 ? reject("エラー") : resolve(result), 1000);
});
return promise;
};
// テスト用の関数
const testAcync = async () => {
try {
console.log("await1");
const result1 = await actionAsync(1);
console.log(`result1: ${result1}`);
console.log("await2");
const result2 = await actionAsync(-1);
console.log(`result2: ${result2}`);
} catch (error) {
console.log(`error: ${error}`);
}
};
testAcync();
/*
await1
result1: 1
await2
error: エラー
*/
// async関数はPromiseを返す
// https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/async_function
// 値を返すとresolveしたPromiseを返す
const resolveAsync = async (result: number) => result;
// 例外や値をスローした場合はrejectされたPromiseを返す
const rejectAsync = async (message: string) => {
throw message;
}
// テスト用の関数
const testAcync = async () => {
try {
console.log("await1");
const result1 = await resolveAsync(1);
console.log(`result1: ${result1}`);
console.log("await2");
const result2 = await rejectAsync("エラー");
console.log(`result2: ${result2}`);
} catch (error) {
console.log(`error: ${error}`);
}
};
testAcync();
/*
await1
result1: 1
await2
error: エラー
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment