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?

[JavaScript][Synchronous / Asynchronous] 非同期処理の雛形

Posted at

1. Promiseを生成する(Producer)

function doSomethingAsync(value) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (value > 0) {
        resolve(value);
      } else {
        reject(new Error("value must be > 0"));
      }
    }, 1000);
  });
}

2. then / catch で Promise を消費する(Consumer)

function consumeWithThen(value) {
  return doSomethingAsync(value)
    .then((result) => {
      console.log(result);
      return result + 10;
    })
    .then((result) => {
      console.log(result);
      return result;
    })
    .catch((error) => {
      console.error(error);
      throw error;
    });
}

3. async / await で Promise を消費する(Consumer)

async function consumeWithAsyncAwait(value) {
  try {
    const result1 = await doSomethingAsync(value);
    console.log(result1);

    const result2 = await doSomethingAsync(result1 + 1);
    console.log(result2);

    return result2;
  } catch (error) {
    console.error(error);
    throw error;
  }
}

4. fetch + then(Consumer)

function fetchUserWithThen(userId) {
  const url = `https://api.example.com/users/${userId}`;

  return fetch(url)
    .then((response) => {
      return response.json();
    })
    .then((data) => {
      console.log(data);
      return data;
    })
    .catch((error) => {
      console.error(error);
      throw error;
    });
}

5. fetch + async / await(Consumer)

async function fetchUserWithAsyncAwait(userId) {
  try {
    const url = `https://api.example.com/users/${userId}`;
    const response = await fetch(url);
    const data = await response.json();

    console.log(data);
    return data;
  } catch (error) {
    console.error(error);
    throw error;
  }
}

6. Promise.all + then(Consumer)

function buildUsersWithPromiseAll() {
  return Promise.all([
    fetch("https://api.example.com/users/1").then((res) => res.json()),
    fetch("https://api.example.com/users/2").then((res) => res.json()),
    fetch("https://api.example.com/users/3").then((res) => res.json()),
  ]).then((response) => {
    const user1 = response[0];
    const user2 = response[1];
    const user3 = response[2];

    return {
      user1,
      user2,
      user3,
    };
  });
}

7. Promise.all + async / await(Consumer)

async function buildUsersWithAsyncAwaitAndAll() {
  const arr = await Promise.all([
    fetch("https://api.example.com/users/1").then((res) => res.json()),
    fetch("https://api.example.com/users/2").then((res) => res.json()),
    fetch("https://api.example.com/users/3").then((res) => res.json()),
  ]);

  const user1 = arr[0];
  const user2 = arr[1];
  const user3 = arr[2];

  return {
    user1,
    user2,
    user3,
  };
}

8. fetchJson を自作する(Producer)

function fetchJson(url) {
  return fetch(url).then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error: ${response.status}`);
    }
    return response.json();
  });
}

9. fetchJson + Promise.all(Consumer)

function buildUsersWithFetchJson() {
  return Promise.all([
    fetchJson("https://api.example.com/users/1"),
    fetchJson("https://api.example.com/users/2"),
    fetchJson("https://api.example.com/users/3"),
  ]).then((users) => {
    return {
      user1: users[0],
      user2: users[1],
      user3: users[2],
    };
  });
}

10. fetchJson + async / await + Promise.all(Consumer)

async function buildUsersFinal() {
  const arr = await Promise.all([
    fetchJson("https://api.example.com/users/1"),
    fetchJson("https://api.example.com/users/2"),
    fetchJson("https://api.example.com/users/3"),
  ]);

  return {
    user1: arr[0],
    user2: arr[1],
    user3: arr[2],
  };
}
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?