async await 과제2

KoEunseo·2022년 7월 27일
0

javascript

목록 보기
18/32

Node.js : 비동기 기반.
fs: 파일시스템.
여기서는 readFile을 사용한다.

https://nodejs.org/dist/latest-v16.x/docs/api/fs.html#filehandlereadfileoptions

fs.readFile(path[,options], callback)

path: 파일이름, 경로
options: object, string, encoding
callback: 전달인자로 err, data
return: Promise

인코딩이 지정되지 않은 경우 Buffer 객체 반환. 보통 'utf8'을 입력한다.
인코딩이 지정되면 데이터는 문자열이 된다.


callback.js

const getDataFromFile = function (filePath, callback) {
  fs.readFile(filePath, 'utf8', (err, data)=> {
    if(err) {
      callback(err, null);
    } else {
      callback(null, data);
    }
  });
};

promiseConstructor.js

const getDataFromFilePromise = filePath => {
  return new Promise((resolve, reject)=> {
    fs.readFile(filePath, 'utf-8', (err, data)=> {
      if(err){
        reject(err);
      } else {
        resolve(data);
      }
    });
  })
};

basicChaining.js

const user1Path = path.join(__dirname, 'files/user1.json');
const user2Path = path.join(__dirname, 'files/user2.json');

const readAllUsersChaining = () => {
  let result = [];
  return getDataFromFilePromise(user1Path)
    .then((data)=> {result.push(JSON.parse(data));
    return getDataFromFilePromise(user2Path)
      .then((data)=> {result.push(JSON.parse(data));
      return result;
    })
  })
}

const readAllUsersChaining = () => {
  let result = [];
  return getDataFromFilePromise(user1Path)
    .then((value) => {
    let user1 = JSON.parse(value)
    result.push(user1)
    return getDataFromFilePromise(user2Path)
  }).then((value)=> {
    let user2 = JSON.parse(value)
    result.push(user2)
    return result;
  })
}
return getData(user1path)
  .then((user1)=> {
    return getData(user2path)
    .then((user2)=> {
      return [JSON.parse(user1), JSON.parse(user2)];
    })
  })

단점!

user100까지 있다면 promise hell이 열린다^^


promiseAll

const readAllUsers = () => {
  return Promise.all([
    getDataFromFilePromise(user1Path), 
    getDataFromFilePromise(user2Path)]) //Promise 반환
    .then((data)=> {
      return data.map(el => JSON.parse(el));
    });
};

const readAllUsers = () => {
  return Promise.all([
    getDataFromFilePromise(user1Path), 
    getDataFromFilePromise(user2Path)]) //Promise 반환
    .then(value => [JSON.parse(el[0]), JSON.parse(el[1])])
};

주어진 프로미스 중 하나가 거부하는 경우 거부가 리턴된다.
then으로 이어주지 않아도 됨! 배열로 한번에 리턴한다


asyncAwait.js

//1
const readAllUsersAsyncAwait = async () => {
  return [
    JSON.parse(await getDataFromFilePromise(user1Path)),
    JSON.parse(await getDataFromFilePromise(user2Path)),
  ]
}
//2
const user1 = await getData(user1path)
const user2 = await getData(user2path)

return [JSON.parse(user1), JSON.parse(user2)]

profile
주니어 플러터 개발자의 고군분투기

0개의 댓글