Promiseとasync、awaitの使い方を理解するために書いたサンプルコード。
setTimeoutを使って1秒後に画面に文字列を出力する。
Promiseとthen()
Promiseオブジェクトの生成とthen()メソッドの利用例。
<html>
<head>
<meta charset="utf-8"/>
<title>Promiseとthen()</title>
</head>
<body>
<button onclick="main()">Run</button>
<div id="output">
</div>
<script>
function print(text) {
const element = document.getElementById('output');
element.innerText = element.innerText + text + '\n';
}
function main() {
const promise = slowFunction();
promise.then(result => {
print(result);
})
}
function slowFunction() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Result");
}, 1000);
});
}
</script>
</body>
</html>
Promiseとthen() - JSFiddle
Promiseオブジェクトの例外処理、reject()とcatch() メソッドを使う。
reject()を呼ぶと、catch()メソッドに渡したコールバック関数が実行される。
<html>
<head>
<meta charset="utf-8"/>
<title>Promiseとreject、catch()</title>
</head>
<body>
<button onclick="main()">Run</button>
<div id="output">
</div>
<script>
function print(text) {
const element = document.getElementById('output');
element.innerText = element.innerText + text + '\n';
}
function main() {
const promise = slowFunction();
promise.then(result => {
print("Success");
}).catch((message) => {
print(message);
})
}
function slowFunction() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject("Error!");
}, 1000);
});
}
</script>
</body>
</html>
Promiseとreject、catch() - JSFiddle
Promiseとthrow
then()メソッドに渡したコールバック関数内で例外を発生させる場合はthrowを使う。
catchメソッドに渡したコールバック関数が呼ばれる。
<html>
<head>
<meta charset="utf-8"/>
<title>Promiseとthrow、catch()</title>
</head>
<body>
<button onclick="main()">Run</button>
<div id="output">
</div>
<script>
function print(text) {
const element = document.getElementById('output');
element.innerText = element.innerText + text + '\n';
}
function main() {
const promise = slowFunction();
promise.then(result => {
throw new Error("Error!");
}).catch((error) => {
print(error);
})
}
function slowFunction() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Result");
}, 1000);
});
}
</script>
</body>
</html>
Promiseとthrow、catch() - JSFiddle
Promiseをawait構文で待つ
Promiseオブジェクトの処理が終わるのをawait構文で待つ例。
<html>
<head>
<meta charset="utf-8"/>
<title>Promiseとawait構文</title>
</head>
<body>
<button onclick="main()">Run</button>
<div id="output">
</div>
<script>
function print(text) {
const element = document.getElementById('output');
element.innerText = element.innerText + text + '\n';
}
async function main() {
result = await slowFunction();
print(result);
}
function slowFunction() {
return new Promise(resolve => {
setTimeout(() => {
resolve("Result");
}, 1000);
});
}
</script>
</body>
</html>
Promiseとawait構文 - JSFiddle
asyncとawait
async functionで関数を実装すれば、Promiseの発行を減らせるのと、then()のメソッドチェーン地獄がマシになる
<html>
<head>
<meta charset="utf-8"/>
<title>asyncとawait</title>
</head>
<body>
<button onclick="main()">Run</button>
<div id="output">
</div>
<script>
function print(text) {
const element = document.getElementById('output');
element.innerText = element.innerText + text + '\n';
}
async function main() {
result = await slowFunction();
print(result);
}
async function slowFunction() {
await new Promise(resolve => setTimeout(resolve, 1000));
return "Result";
}
</script>
</body>
</html>
asyncとawait - JSFiddle
async、awaitと例外処理
async、awaitを使う場合、例外はthrowで発生させて、try catch構文で処理できる。
<html>
<head>
<meta charset="utf-8"/>
<title>asyncとawait、throw()</title>
</head>
<body>
<button onclick="main()">Run</button>
<div id="output">
</div>
<script>
function print(text) {
const element = document.getElementById('output');
element.innerText = element.innerText + text + '\n';
}
async function main() {
try {
result = await slowFunction();
print(result);
} catch (error) {
print(error);
}
}
async function slowFunction() {
await new Promise(resolve => setTimeout(resolve, 1000));
throw new Error("Error in async function!");
return "Result";
}
</script>
</body>
</html>
asyncとawait、throw() - JSFiddle
参考