Skip to content

Instantly share code, notes, and snippets.

@aidiary
Last active Mar 16, 2020
Embed
What would you like to do?
promiseの使い方

Promise Tutorial

  • https://www.youtube.com/watch?v=PoRJizFvM7s
  • Promiseオブジェクトを返す
  • resolveとrejectの二つの引数を取る
  • resolve() を返したら呼び出し元で then() で受けられる
  • reject() を返したら呼び出し元で catch() で受けられる
const posts = [
  { title: "Post One", body: "This is post one" },
  { title: "Post Two", body: "This is post two" }
];

function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.forEach((post, index) => {
      output += `<li>${post.title}</li>`;
    });
    document.body.innerHTML = output;
  }, 1000);
}

function createPost(post) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      posts.push(post);

      const error = false;

      if (!error) {
        resolve();
      } else {
        reject("Error: Something went wrong");
      }
    }, 2000);
  });
}

createPost({ title: "Post Three", body: "This is post three" })
  .then(getPosts)
  .catch(err => console.log(err));
  • async / await を使うと下のように then を使わずに簡単に書ける
// Async / Await
async function init() {
  await createPost({ title: "Post Three", body: "This is post three" });
  getPosts();
}

init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment