0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Promiseのresolve()を他の場所で呼び出してawaitでの待ちのを終了する

Posted at

確認した環境

  • Google Chrome Version 93.0.4577.63 (Official Build) (64-bit)
  • 今回、試した記述方法が、あらゆる環境で動作するかは把握できていない

内容

  • Promiseのresolve()は、「Promiseクラスのコンストラクタの第1引数に渡す関数内」でしか呼び出してはいけないと思っていたが、
  • resolve()を参照する変数を別のスコープに用意して、呼び出しても期待通りに動作した
  • Pormiseオブジェクトを返却する関数を用意しないといけないとも勘違いしていた
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Promise</title>
</head>
<body>
<div id="button" style="width:200px; background-color:darkgrey; border: 1px solid black;">Click me!<div>
</body>
<script>
    (async () => {
        let clicked;
        const waitingForYourClick = new Promise(resolve => clicked = resolve);
        const button = document.querySelector("#button");
        button.addEventListener("click", clicked);
        console.log("Waiting");
        await waitingForYourClick;
        console.log("Done");
        button.removeEventListener("click", clicked);
        button.innerHTML = "Clicked!";
    })();
</script>
</html>

await.gif

感想

  • async/awaitが好きすぎて、Promiseは書きたくないと思っていたけど、Promiseも好きになれた
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?