Skip to content

20240909 非同期処理(JavaScript) #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 89 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from 76 commits
Commits
Show all changes
89 commits
Select commit Hold shift + click to select a range
896a018
package.json
taichihub Sep 6, 2024
ac18702
コールバック(エラーハンドリングあり)
taichihub Sep 6, 2024
ae35975
コールバック(エラーハンドリングなし)
taichihub Sep 6, 2024
cb0ab66
コールバック関連ファイルディレクトリ配置変更
taichihub Sep 6, 2024
18aca3f
promise処理共通部分
taichihub Sep 6, 2024
c252788
promise(エラーハンドリングあり)
taichihub Sep 6, 2024
ebd6735
promise(エラーハンドリングなし)
taichihub Sep 6, 2024
df009bb
db.jsの配置ディレクトリ変更
taichihub Sep 9, 2024
cb119d0
db.jsの配置場所変更により修正
taichihub Sep 9, 2024
e8d6dc1
async/awaitを使用して非同期処理実装
taichihub Sep 9, 2024
bb8ad1b
Prettier実行/ログ出力をprocessに修正
taichihub Sep 9, 2024
c8ca03b
不必要に削除したファイルを復元
taichihub Oct 4, 2024
e91e6c1
ファイル名タイポ修正
taichihub Oct 4, 2024
a3d569c
SQLiteデータベースに接続した際にdb.js内でログを出力処理まで入れた
taichihub Oct 16, 2024
f357a12
db.jsからSQLiteデータベース接続処理をimportして使用するようにした
taichihub Oct 16, 2024
fd771bb
エラーありバージョンの出力内容を全ファイル統一させた
taichihub Oct 16, 2024
eebbbe5
各ファイル名を適切な名詞形に変更
taichihub Oct 16, 2024
2fc8099
データベース接続の出力をprocessではなくconsole.logで対応
taichihub Oct 16, 2024
ffd1a0b
SQL文修正(条件を排除)
taichihub Oct 16, 2024
8953eac
SQL文抽出方法変更/使用されていない変数をアンダースコアにして明示化
taichihub Oct 16, 2024
feb7c31
(callback/エラーあり)ドキュメントの要件1〜4を満たすようプログラムを修正
taichihub Oct 16, 2024
4f3a9f2
SQL文抽出条件変更/バッククオートからダブルクオートへ
taichihub Oct 16, 2024
184553f
ログの出力をprocessからconsoleに変更
taichihub Oct 16, 2024
1ed18fc
(Promise/エラーあり)ドキュメントの要件1〜4を満たすようプログラムを修正
taichihub Oct 21, 2024
415cfcb
ログ出力をprocessからconsoleに修正
taichihub Oct 21, 2024
90a15e8
不必要なバッククオートをダブルクオートに修正/SQL文のテーブル作成条件を修正
taichihub Oct 21, 2024
771d413
ログ出力をprocessからconsoleに変更
taichihub Oct 21, 2024
5a7a9c4
エラーなしのプログラム内のエラーハンドリング削除
taichihub Oct 21, 2024
132f715
各SQL文修正
taichihub Oct 21, 2024
b0a51bd
不必要なバッククオートをダブルクオートに変更
taichihub Oct 21, 2024
3aec3ec
(callback/エラーなし)ログの出力をprocessからconsoleに変更
taichihub Oct 21, 2024
f576fe0
(async/await,エラーあり)各SQL文修正
taichihub Oct 21, 2024
e66bc94
(async/await,エラーあり)ログ出力をprocessからconsoleに変更
taichihub Oct 21, 2024
941c2c5
不必要なcatch文を削除
taichihub Oct 21, 2024
77b3274
(async/await,エラーあり)ドキュメントの要件1〜4を満たすようプログラムを修正
taichihub Oct 21, 2024
e6b4987
(async/await,エラーあり)データ挿入方法の冗長性を解消
taichihub Oct 21, 2024
d713856
(async/await,エラーあり)Top-level awaitを用いて修正
taichihub Oct 22, 2024
dc07b1e
(async/await,エラーなし)不必要なエラーハンドリングを削除
taichihub Oct 22, 2024
6c496ca
(async/await,エラーなし)SQL文修正
taichihub Oct 22, 2024
e5f5724
(async/await,エラーなし)ログの出力方法をprocessからconsoleに変更
taichihub Oct 22, 2024
638b579
(async/await,エラーなし)Top-level awaitを使用して修正
taichihub Oct 22, 2024
027c90f
Databaseクラスを作成し、再利用性を高めた
taichihub Oct 22, 2024
b79e014
importの内容の変更、データベースの読み込み
taichihub Oct 22, 2024
66d5938
「データベース接続を閉じました。」の文言を出力するタイミングを修正した
taichihub Oct 22, 2024
a6ca38b
ファイル名をdb.jsからdb_operations.jsに修正
taichihub Oct 22, 2024
4d4fbfe
resolve時に渡す値の記述方法を修正
taichihub Oct 24, 2024
217c638
不必要なパラメータ引数を削除
taichihub Oct 29, 2024
48ca46d
エラーハンドリングのスコープを修正
taichihub Oct 29, 2024
bfeab6b
エラー発生の条件を変更
taichihub Oct 29, 2024
7b8d8af
Databaseクラスを解消して実装し直し
taichihub Oct 30, 2024
48c3c05
存在しないカラムを指定することでエラーを発生させるようにした
taichihub Oct 30, 2024
21ae886
promiseのネストを解消
taichihub Oct 30, 2024
1a49633
INSERT文に対してtry...catch文を追加
taichihub Oct 30, 2024
df85e06
instanceof演算子を使用してエラーの捕捉範囲を限定的にした
taichihub Oct 30, 2024
78dc37a
tun,allメソッドのデフォルト引数を削除
taichihub Oct 30, 2024
be86392
無名関数を使用していたところをアロー関数に修正
taichihub Nov 6, 2024
f3560a7
エラーメッセージ出力内容を修正
taichihub Nov 6, 2024
34623e9
「レコードが存在しません」のエラー文出力部分を他のエラーにも対応できるよう修正
taichihub Nov 6, 2024
40bd3b8
closeメソッドが正常に完了してからデータベース接続終了のログを出すようにした
taichihub Nov 6, 2024
016ef1b
エラーハンドリング周りの処理を修正
taichihub Nov 6, 2024
9a77510
catch文の中の処理を例外に関する処理のみにした
taichihub Nov 6, 2024
983d77b
dbが正常に作成された後に後続の処理が働くようにした
taichihub Nov 12, 2024
1713f95
closeのPromise結果が返ってきてから後続のthenが働くように修正した
taichihub Nov 12, 2024
a1ebfcb
dbの変数に依存しない形に修正した
taichihub Nov 12, 2024
736ca2e
finallyが実行される内容と範囲を調整
taichihub Nov 12, 2024
2eb8f3d
dbとdbReadyの処理を統一
taichihub Nov 14, 2024
1618ed5
pritterの設定を変更して全ファイルに反映
taichihub Nov 14, 2024
bc18241
特定のエラーだけを捕捉するように修正した
taichihub Nov 14, 2024
b0b894e
各ファイルにshebangを追加
taichihub Nov 19, 2024
b73eabe
console.log行の次に空行を挿入
taichihub Nov 19, 2024
bb30353
db接続処理を関数化
taichihub Nov 19, 2024
11cfa5a
prettier・eslintの設定を初期化
taichihub Nov 19, 2024
ce5f300
不必要なエラーハンドリングを削除
taichihub Nov 19, 2024
96bd6ae
期待するエラーをStringオブジェクトで判別
taichihub Nov 19, 2024
703567d
insert処理をPromiseのコードと統一させた
taichihub Nov 19, 2024
d76d7ea
正常時のconsole.log行をなくした
taichihub Nov 19, 2024
6845398
実行権限を付与した
taichihub Nov 20, 2024
d143565
letをconstに変更
taichihub Nov 20, 2024
b748124
期待するエラーのみを捕捉するように修正した
taichihub Nov 20, 2024
0495259
簡潔文体にした
taichihub Nov 20, 2024
41431bb
引数の中で変数を代入するのをやめた
taichihub Nov 26, 2024
bb6d305
runメソッドの実行部分で簡潔文体を使用するようにした
taichihub Nov 26, 2024
6fe6e9e
finally文を簡潔文体にした
taichihub Nov 26, 2024
9eb40da
エラー合致条件にエラーコードを追加
taichihub Nov 26, 2024
f32f5e5
エラーの捕捉範囲を狭めて期待するエラーのみを捕捉するようにした
taichihub Nov 30, 2024
f248bf9
sqlite3.Databseと自分で定義した関数のインタフェースを統一させた
taichihub Nov 30, 2024
3c01eed
引数名をドキュメントと合わせた
taichihub Dec 12, 2024
a740307
エラー捕捉条件を修正
taichihub Dec 12, 2024
f92b465
レコード取得時のエラー捕捉方法修正
taichihub Dec 16, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions 03.asynchronous/async_await/existing_error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/env node

import { createDatabase, run, all, close } from "../db_operations.js";

let db = await createDatabase();
console.log("メモリ内のSQLiteデータベースに接続しました。");

try {
await run(
db,
"CREATE TABLE books (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL UNIQUE)",
);
console.log("テーブルが作成されました。");

try {
const result = await run(db, "INSERT INTO books (title) VALUES (?)", [
"Node.js入門",
]);
console.log(`行が追加されました。id: ${result.lastID}`);
await run(db, "INSERT INTO books (title) VALUES (?)", ["Node.js入門"]);
} catch (err) {
if (
String(err).includes(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

以下のような文字列を例外として送出すると条件にマッチしてしまうと思いますよ。

try {
  throw "The following error has not occurred: UNIQUE contraint failed";
} catch (...) {
  ...
}

Copy link
Owner Author

@taichihub taichihub Nov 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer
条件はSQLITE_CONSTRAINT: UNIQUE constraint failed: books.titleが含まれているかであり、The following error has not occurred: UNIQUE contraint failedは期待するエラー文と異なるので条件にマッチしないかと思います。

実際に上記の例外を創出させてみました。

対象部分のコード

  try {
    throw "The following error has not occurred: UNIQUE contraint failed";
  } catch (err) {
    if (
      String(err).includes(
        "SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title",
      )
    ) {
      console.error(`エラーが発生しました: ${String(err)}`);
    } else {
      console.error(`期待外のエラーが発生しました: ${String(err)}`);
      throw err;
    }
  }

実行結果

chiroru@MacBook-Pro-4 async_await % ./existing_error.js
メモリ内のSQLiteデータベースに接続しました。
テーブルが作成されました。
期待外のエラーが発生しました: The following error has not occurred: UNIQUE contraint failed
データベース接続を閉じました。

node:internal/modules/run_main:129
    triggerUncaughtException(
    ^
The following error has not occurred: UNIQUE contraint failed
(Use `node --trace-uncaught ...` to show where the exception was thrown)

Node.js v20.17.0

Copy link

@cafedomancer cafedomancer Nov 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ああ、すみません、文字列に誤りがありましたが、文字列の中身は重要ではないです。以下だとマッチするはずです。

try {
  throw "The following error has not occurred: SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title";
} catch (...) {
  ...
}

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer

  • SQLiteのエラーNoも判定材料に入れることで予期せぬマッチを避けるようにしました。
  try {
    const result = await run(db, "INSERT INTO books (title) VALUES (?)", [
      "Node.js入門",
    ]);
    console.log(`行が追加されました。id: ${result.lastID}`);
    await run(db, "INSERT INTO books (title) VALUES (?)", ["Node.js入門"]);
  } catch (err) {
    if (
      err.errno === 19 &&
      String(err).includes(
        "SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title",
      )
    ) {
      console.error(`エラーが発生しました: ${String(err)}`);
    } else {
      throw err;
    }
  }

実行結果

chiroru@MacBook-Pro-4 async_await % ./existing_error.js
メモリ内のSQLiteデータベースに接続しました。
テーブルが作成されました。
行が追加されました。id: 1
エラーが発生しました: Error: SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title
エラーが発生しました: SQLITE_ERROR: no such table: nonexistent_table
テーブルが削除されました。
データベース接続を閉じました。
chiroru@MacBook-Pro-4 async_await % 

記載していただいた文での検証

  • スローした文で条件にマッチしておらず、期待通りに条件分岐ができている。
  try {
    throw "The following error has not occurred: SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title";
  } catch (err) {
    if (
      err.errno === 19 &&
      String(err).includes(
        "SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title",
      )
    ) {
      console.error(`エラーが発生しました: ${String(err)}`);
    } else {
      throw err;
    }
  }

実行結果

chiroru@MacBook-Pro-4 async_await % ./existing_error.js
メモリ内のSQLiteデータベースに接続しました。
テーブルが作成されました。
データベース接続を閉じました。

node:internal/modules/run_main:129
    triggerUncaughtException(
    ^
The following error has not occurred: SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title
(Use `node --trace-uncaught ...` to show where the exception was thrown)

Node.js v20.17.0
chiroru@MacBook-Pro-4 async_await % 

Copy link

@cafedomancer cafedomancer Nov 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ちょっと極端ですが、以下のようなコードだと条件にマッチしてしまうと思いますよ。やみくもに条件を増やすのではなく、根本的な対応を考えてください。

class MyString extends String {
  constructor(errno, string) {
    super(string);
    this.errno = errno;
  }
}

try {
  throw new MyString(19, "The following error has not occurred: SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title");
} catch (...) {
  ...
}

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer
捕捉するエラーにtitleの制約を設けて今回のケース以外にエラーが捕捉されないように修正しました。

  const title = "Node.js入門";
  try {
    const result = await run(db, "INSERT INTO books (title) VALUES (?)", [
      title,
    ]);
    console.log(`行が追加されました。id: ${result.lastID}`);
    await run(db, "INSERT INTO books (title) VALUES (?)", [title]);
  } catch (err) {
    if (
      title === "Node.js入門" &&
      String(err).includes(
        "SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title",
      )
    ) {
      console.error(`エラーが発生しました: ${String(err)}`);
    } else {
      throw err;
    }
  }

"SQLITE_CONSTRAINT: UNIQUE constraint failed: books.title",
)
) {
console.error(`エラーが発生しました: ${String(err)}`);
} else {
throw err;
}
}

try {
await all(db, "SELECT * FROM nonexistent_table WHERE id = ?", [-1]);
} catch (err) {
console.error(`エラーが発生しました: ${err.message}`);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

この部分は例外が握り潰されてしまっているような。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer
insertの処理同様、期待するエラーのみを捕捉するように修正しました。

  try {
    await all(db, "SELECT * FROM nonexistent_table WHERE id = ?", [-1]);
  } catch (err) {
    if (
      String(err).includes("SQLITE_ERROR: no such table: nonexistent_table")
    ) {
      console.error(`エラーが発生しました: ${err.message}`);
    } else {
      throw err;
    }
  }


await run(db, "DROP TABLE books");
console.log("テーブルが削除されました。");
} finally {
await close(db);
console.log("データベース接続を閉じました。");
}
30 changes: 30 additions & 0 deletions 03.asynchronous/async_await/nonexistent_error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/env node

import { createDatabase, run, all, close } from "../db_operations.js";

let db = await createDatabase();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

この変数は再代入されないので let で定義する必要はないですね。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer
constに変更しました。

const db = await createDatabase();

console.log("メモリ内のSQLiteデータベースに接続しました。");

try {
await run(
db,
"CREATE TABLE books (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL UNIQUE)",
);
console.log("テーブルが作成されました。");

const result = await run(db, "INSERT INTO books (title) VALUES (?)", [
"Node.js入門",
]);
console.log(`行が追加されました。id: ${result.lastID}`);

const rows = await all(db, "SELECT * FROM books");
rows.forEach((row) => {
console.log(`${row.id}: ${row.title}`);
});

await run(db, "DROP TABLE books");
console.log("テーブルが削除されました。");
} finally {
await close(db);
console.log("データベース接続を閉じました。");
}
46 changes: 46 additions & 0 deletions 03.asynchronous/callback/existing_error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!/usr/bin/env node

import sqlite3 from "sqlite3";

const db = new sqlite3.Database(":memory:", () => {
console.log("メモリ内のSQLiteデータベースに接続しました。");

db.run(
"CREATE TABLE books (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL UNIQUE)",
() => {
console.log("テーブルが作成されました。");

db.run(
"INSERT INTO books (title) VALUES (?)",
["Node.js入門"],
function () {
console.log(`行が追加されました。id: ${this.lastID}`);

db.run(
"INSERT INTO books (title) VALUES (?)",
["Node.js入門"],
(err) => {
if (err) {
console.error(`エラーが発生しました: ${err.message}`);
}

db.all("SELECT content FROM books", (err) => {
if (err) {
console.error(`エラーが発生しました: ${err.message}`);
}

db.run("DROP TABLE books", () => {
console.log("テーブルが削除されました。");

db.close(() => {
console.log("データベース接続を閉じました。");
});
});
});
},
);
},
);
},
);
});
36 changes: 36 additions & 0 deletions 03.asynchronous/callback/nonexistent_error.js

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

見通していたのかもしれませんが、shebang がないのにこのファイルに実行権限が付与されています。promise/nonexisting_error.js, promise/existent_error.js についても同様です。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer
各ファイルにshebangを追記いたしました🙇‍♂️

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shebang を付けてもファイルに実行権限が付与されていなければ意味がないですよ。どちらでもいいですが、shebang なし・実行権限なしに統一する、shebang あり、実行権限ありに統一する、のどちらかの対応を行ってください。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer
callback配下、promise配下、async_await配下の全てのファイルに実行権限を付与しました。
これで「shebangあり・実行権限あり」に統一できました。

chiroru@MacBook-Pro-4 03.asynchronous % ls -l callback/ promise/ async_await 
async_await:
total 16
-rwxr-xr-x  1 chiroru  staff  1270 11 19 19:23 existing_error.js
-rwxr-xr-x  1 chiroru  staff   883 11 19 17:29 nonexistent_error.js

callback/:
total 16
-rwxr-xr-x  1 chiroru  staff  1357 11 19 17:23 existing_error.js
-rwxr-xr-x  1 chiroru  staff  1026 11 19 17:28 nonexistent_error.js

promise/:
total 16
-rwxr-xr-x  1 chiroru  staff  1225 11 19 17:31 existing_error.js
-rwxr-xr-x  1 chiroru  staff  1046 11 19 17:29 nonexistent_error.js

Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env node

import sqlite3 from "sqlite3";

const db = new sqlite3.Database(":memory:", () => {
console.log("メモリ内のSQLiteデータベースに接続しました。");

db.run(
"CREATE TABLE books (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL UNIQUE)",
() => {
console.log("テーブルが作成されました。");

db.run(
"INSERT INTO books (title) VALUES (?)",
["Node.js入門"],
function () {
console.log(`行が追加されました。id: ${this.lastID}`);

db.all("SELECT * FROM books", (_, rows) => {
rows.forEach((row) => {
console.log(`${row.id}: ${row.title}`);
});

db.run("DROP TABLE books", () => {
console.log("テーブルが削除されました。");

db.close(() => {
console.log("データベース接続を閉じました。");
});
});
});
},
);
},
);
});
49 changes: 49 additions & 0 deletions 03.asynchronous/db_operations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import sqlite3 from "sqlite3";

export const createDatabase = () => {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

元の sqlite3.Database 関数ではデータベースファイルのパスを指定できるようになっていたはずです。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer
すみません。「元の sqlite3.Database 関数ではデータベースファイルのパスを指定できるようになっていたはずです。」の文章から何を修正したら良いのかが推測できなかったので、もう少しブレイクダウンして説明していただきたいです🙇‍♂️

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sqlite3.Database() 関数の元の機能を維持してください。つまり、sqlite3.Database() 関数のインタフェースと自分で定義した関数のインタフェースを一致させてください。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer
引数にfilenameをとるようにし、呼び出す側でインメモリデータベースを指定するように修正しました。
引数名のfilenameは公式ドキュメントで記載されている文言と一致させました。
https://github.com/TryGhost/node-sqlite3/wiki/API

createDatabase

export function createDatabase(filename) {
  return new Promise((resolve, reject) => {
    const db = new sqlite3.Database(filename, (err) => {
      if (err) {
        reject(err);
      } else {
        resolve(db);
      }
    });
  });
}

promise

createDatabase(":memory:")
  .then((resolvedDB) => {
.....

async/await

let db = await createDatabase(":memory:");
.....

return new Promise((resolve, reject) => {
const db = new sqlite3.Database(":memory:", (err) => {
if (err) {
reject(err);
} else {
resolve(db);
}
});
});
};

export function run(db, sql, params) {
return new Promise((resolve, reject) => {
db.run(sql, params, function (err) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

コメントし忘れていましたが、関数はその外部の変数に依存しないようにしてください。再利用性が下がるからです。他に定義したデータベースとこれらの関数を組み合わせて使おうと思っても、現状の実装ではそうできないです。

Copy link
Owner Author

@taichihub taichihub Nov 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@cafedomancer

db_operations.jsの変更点

  • run・all・closeメソッドの引数にdbを追加した
  • db変数はデータベース作成のみの責務にした
  • dbReady変数でdb変数に格納されたデータベースが正常に接続されているかをPromiseで返すようにした
export const db = new sqlite3.Database(":memory:");

export const dbReady = new Promise((resolve, reject) => {
  db.once("open", () => {
    console.log("メモリ内のSQLiteデータベースに接続しました。");
    resolve();
  });
  db.once("error", (err) => reject(err));
});
export function run(db, sql, params) {
export function all(db, sql, params) {
export function close(db) {

promise/.js、async_await/.jsの変更点

  • db、dbReady変数をimportするようにした
  • dbReadyで返ってくるPromiseの結果を待って後続の処理を続けるようにした
    これによって、正常にdb接続が完了してから後続の処理が働くようになった。

promise/*.js

import { db, dbReady, run, close } from "../db_operations.js";

dbReady
  .then(() => {
    return run(
      db,
      "CREATE TABLE books (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL UNIQUE)",
    );
  })
..........

async_await/*.js

import { db, dbReady, run, all, close } from "../db_operations.js";

await dbReady;

try {
  await run(
    db,
    "CREATE TABLE books (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL UNIQUE)",
  );
..........

if (err) {
reject(err);
} else {
resolve(this);
}
});
});
}

export function all(db, sql, params) {
return new Promise((resolve, reject) => {
db.all(sql, params, (err, rows) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
}

export function close(db) {
return new Promise((resolve, reject) => {
db.close((err) => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
Loading