1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

reader.onloadの実行完了を待つ

Posted at
const hoge = () => {
  let base64File: string | null = null;
  const reader = new FileReader();
  reader.onload = () => {
    if (!reader.result) return;
    if (typeof reader.result !== "string") return;
    base64File = reader.result.split(",")[1];
  };
  reader.readAsDataURL(file);
  // 以降の処理
}

みたいなコードを書いた時、base64Fileに値が入ったのを確認してから次の処理に移りたい場合がある

async/awaitでなんとかできたので備忘

const hoge = async () => {
  const base64File = await new Promise<string>((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => {
      if (!reader.result || typeof reader.result !== "string") {
        reject();
        return;
      }
      resolve(reader.result.split(",")[1]);
    };
    reader.readAsDataURL(file);
  });
  // 以降の処理
}

readerをあんまり理解していないので、もっと良いコードがあれば教えてください

1
1
3

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?