analogcoding

6/21 / promise , async await 본문

Be well coding/In Immersive

6/21 / promise , async await

be well 2019. 6. 22. 10:27

Toy 13번 문제 . tree 구조 , BF search , depth 도 리턴.

 

Tree.prototype.BFSelect = function(filter) {
  let result = [];

  console.log(filter)
  console.log(this)

  function recur(node,depth){
    if(filter(node.value,depth)){
      result.push(node.value);
    }
    if(node.children.length > 0){
      for(let i = 0; i < node.children.length; i++){
        recur(node.children[i],depth +1)
      }
    }
  }
  recur(this,0);
  return result;
  // return an array of values for which the function filter(value, depth) returns true
};

 

비동기함수의 처리를 위한 promise 사용연습.

 

 callback 함수

 

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

/**
 * 아래 함수는 항상 Http Response의 Body를 callback함수에 넘겨주어야 합니다.
 * Request 라이브러리를 사용해 Http request를 보냅니다.
 */
const getBodyFromGetRequest = function(url, callback) {
  request(url, function (err, response, body){
    if(err){
      callback(err,null)
    }
    else {
    callback(err,JSON.parse(body))
    }
  })
};

 

promise 

 

const getDataFromFilePromise = filePath => {
  return new Promise((resolve,reject)=>{
    fs.readFile(filePath,'utf8',(err,data)=>{
      if(err){
        reject(err)
      }
      else {
        resolve(data.split('\n'))
      }
    })
  })
  
};

/**
 * 아래 함수는 항상 Http Response의 Body를 callback함수에 넘겨주어야 합니다.
 */
const getBodyFromGetRequestPromise = url => {
  return new Promise((resolve,reject)=>
  request(url,function(err,Response,body){
    if(err){
      reject(err);
    }
    else {
      resolve(JSON.parse(body))
    }
  })
  )
};

 

util promisify

 

const util = require("util");

const {
  getDataFromFile,
  getBodyFromGetRequest
} = require("../exercises/callBack");

const getDataFromFilePromise = util.promisify(getDataFromFile);

const getBodyFromGetRequestPromise = util.promisify(getBodyFromGetRequest);

 

basicChaining

 

const fs = require("fs");
const util = require("util");

const {
  getBodyFromGetRequestPromise,
  getDataFromFilePromise
} = require("../exercises/promiseConstructor");

const writeFilePromise = util.promisify(fs.writeFile);


const BASE_URL = "https://koreanjson.com/users/";
// readFilePath = read user ID text , 
//  writeFilePath = write userName
const fetchUsersAndWriteToFile = (readFilePath, writeFilePath) => {
  return getDataFromFilePromise(readFilePath)
         .then(ids => ids.map(id => BASE_URL + id))
         .then(id => id.map(urlid => getBodyFromGetRequestPromise(urlid)))
         .then(pend => Promise.all(pend))
         .then(arr => arr.map(obj => obj.name))
         .then(namearr => namearr.map(name => name+'\n'))
         .then(Enames => Enames.join(''))
         .then(names => writeFilePromise(writeFilePath,names)) 
          
}

 

asynAwait

 

const fs = require("fs");
const util = require("util");

const {
  getBodyFromGetRequestPromise,
  getDataFromFilePromise
} = require("../exercises/promiseConstructor");

const writeFilePromise = util.promisify(fs.writeFile);



const BASE_URL = "https://koreanjson.com/users/";

const fetchUsersAndWriteToFileAsync = async (readFilePath, writeFilePath) => {

  const a = await getDataFromFilePromise(readFilePath)

  const b =  a.map(id => BASE_URL + id)

  const c =  b.map(urlid => getBodyFromGetRequestPromise(urlid))

  const d = await Promise.all(c)

  const e = d.map(obj => obj.name)

  const f = e.map(name => name+'\n')

  const g = await f.join('')
  
  return writeFilePromise(writeFilePath,g)
};

'Be well coding > In Immersive' 카테고리의 다른 글

6/24 / DB , SQL  (0) 2019.06.25
6/22 / server flow  (0) 2019.06.24
6/20 / server , express , node.js  (0) 2019.06.20
6/19 / server , RESTFUL API  (0) 2019.06.19
6/18 / server  (0) 2019.06.18
Comments