본문 바로가기

잡부생활

Node Callback / Promise / async&await

 

Callback 문제 예시

const posts = [{ title: "Post One" }, { title: "Post Two" }];
function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.forEach((post, index) => {
      output += post.title + "\n";
    });
    console.log(output);
  }, 1000);
}

function createPost(post) {
  setTimeout(() => {
    posts.push(post);
  }, 2000);
}

getPosts();

createPost({ title: "Post Three" });

 

 

Callback 해결

const posts = [{ title: "Post One" }, { title: "Post Two" }];

function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.forEach((post, index) => {
      output += post.title + "\n";
    });
    console.log(output);
  }, 1000);
}

function createPost(post, callback) {
  setTimeout(() => {
    posts.push(post);
    callback();
  }, 2000);
}

getPosts();
createPost({ title: "Post Three" }, getPosts);

 

 

Callback 해결

const emailExistence = require("email-existence");

const test = cb => {
  emailExistence.check("lluckyy@gscdn.com", function(error, response) {
    cb(response);
  });
};

test(result => {
  console.log(result);
  console.log("test");
});

 

 

Promise

const fetch = require("node-fetch");

const posts = [{ title: "Post One" }, { title: "Post Two" }];

function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.forEach((post, index) => {
      output += post.title + "\n";
    });
    console.log(output);
  }, 1000);
}

function createPost(post) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      posts.push(post);
      // const error = true;
      const error = false;
      if (!error) {
        resolve();
      } else {
        reject("Erorr: Something went wrong");
      }
    }, 2000);
  });
}
// createPost({ title: "Post Theree" })
//   .then(getPosts)
//   .catch(err => console.log(err));

// Promise.all
const promise1 = Promise.resolve("Hello World");
const promise2 = 10;
const promise3 = new Promise((resolve, reject) =>
  setTimeout(resolve, 2000, "Goobye")
);
const promise4 = fetch("https://jsonplaceholder.typicode.com/users").then(res =>
  res.json()
);

Promise.all([promise1, promise2, promise3, promise4]).then(values =>
  console.log(values)
);

 

 

async, await

const fetch = require("node-fetch");

const posts = [{ title: "Post One" }, { title: "Post Two" }];

function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.forEach((post, index) => {
      output += post.title + "\n";
    });
    console.log(output);
  }, 1000);
}

function createPost(post) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      posts.push(post);
      // const error = true;
      const error = false;
      if (!error) {
        resolve();
      } else {
        reject("Erorr: Something went wrong");
      }
    }, 2000);
  });
}
// Async, Await
async function init() {
  await createPost({ title: "Post Theree" });
  getPosts();
}
init();

 

 

async, await, fetch

const fetch = require("node-fetch");

const posts = [{ title: "Post One" }, { title: "Post Two" }];

function getPosts() {
  setTimeout(() => {
    let output = "";
    posts.forEach((post, index) => {
      output += post.title + "\n";
    });
  }, 0);
}

function createPost(post) {
  setTimeout(() => {
    posts.push(post);
  }, 2000);
}

// Async / Await
// async function init() {
//   await createPost({ title: "Post Theree" });
//   await getPosts();
// }
// init();

async function fetchUser() {
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  const data = await res.json();
  const test = await getPosts();
  console.log(data);
  console.log(test);
}

fetchUser();

 

 

응용

const emailExistence = require("email-existence");

const create = () => {
  return new Promise((resolve, reject) => {
    emailExistence.check("lluckyy@gscdn.com", function(error, response) {
      if (error) {
        reject({ err: error });
      } else {
        resolve({ email: response });
      }
    });
  });
};

const hello = () => {
  return "hello";
};

const init = async () => {
  try {
    const result = await create();
    console.log(result);
  } catch (err) {
    console.log(err);
  }
  try {
    const hell = await hello();
    console.log(hell);
  } catch (err) {
    console.log(err);
  }
};

init();

'잡부생활' 카테고리의 다른 글

Babel 6/7  (0) 2019.07.22
OpenVPN, OpenLDAP  (0) 2019.04.23
Node Callback / Promise / async&await  (0) 2019.04.10
Alibaba Cloud ECS 간단 사용기  (0) 2019.03.27
Python locust load test tool  (0) 2018.12.07
HTTP 헤더 모니터링  (0) 2017.12.11