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 1 year has passed since last update.

TypeScriptでPromiseを使っての同期処理を実行

Last updated at Posted at 2023-03-21

はじめに

タイトルの通り。
細かい動作(特にrejectとか)がなんとなくわかっていなかったため、サンプルを交えた書き起こし記事。

確認環境

こちらを参照

サンプルコード

// promiseのテスト使用関数
const promiseTest = (param: number) => {
    return new Promise((resolve, reject) => {
        // 剰余演算で分岐
        if (param % 2 === 0) {
            // 呼び出し側で正常の処理となる
            resolve(0);
        } else {
            // 呼び出し側では、catchでの処理となる
            reject(1);
        }
    })
}

// メイン関数
const main = async () => {
    try {
        // promiseのテスト使用関数呼び出し
        const retcode = await promiseTest(2);
        // resolveで終わった場合はきちんとリターンに入ってくる
        console.log("retcode=", retcode)
    } catch (err) {
        // rejectで終わった場合はcatchの方に入る
        console.log("err=", err)
    }
}

// メイン実行
main();

少し応用

以前、記事として起こしたsocket通信

のプログラムに適用

import * as net from "net";

// ネットワーク設定(事前にコンテナ同士のネットワークグループ設定は必要)
const HOST: string = "python-socket_app_1";
const PORT: number = 50000;
// 送信内容
const SEND_DATA = "send message";

const sendSocekt = () => {
  return new Promise((resolve, reject) => {
    // インスタンス生成
    const client = new net.Socket();

    // 接続処理
    client.connect(PORT, HOST, () => {
      console.log("connected: " + HOST + ":" + PORT);
      // メッセージ送信
      client.write(SEND_DATA);
    });
    // 相手から通信が帰ってきたとき
    client.on("data", (data: Buffer) => {
      console.log("Recieve Data: " + data);
      // 接続破棄
      client.destroy();
    });
    // 破棄したときの処理
    client.on("close", () => {
      console.log("Connection closed");
      resolve(0);
    });
    // エラー処理
    client.on("error", (err: Error) => {
      console.log("Error:", err);
      reject(1);
    });
  }
  )
}


// メイン実行
const main = async () => {
  try{
    // 通常時
    const retcode = await sendSocekt();
    console.log("retcode=", retcode)
  }catch(err){
    // エラー時
    console.log("err=", err)
  } 
}

// メイン実行
main();

※resolveだけつかって0 or 1 返した方が内容的にはシンプル化もしれませんが、、

最後に

いざ使ってみると、自身がわかっていないことはなるべく記事にしていこう、、

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?