Asynchronous


callback

let printString = function(str){
  setTimeout(
    ()=>{
      console.log(str);
    },
    Math.floor(Math.random()*100)+1
  )
}

let printAll = () =>{
  printString("A");
  printString("B");
  printString("C");
}
printAll();
上に表示されているコードは順番に実行されません.
順番に解決するためにはCalbackが必要です.
Calbackを順番に実行する方法を試してみます.
	
  let printString = (string, callback) => {
    setTimeout(
      () => {
        console.log(string)
        callback()
      }, 
      Math.floor(Math.random() * 100) + 1
    )
  }
 
  let printAll = () => {
    printString("A", () => {
      printString("B", () => {
        printString("C", () => {})
      })
    })
  }
  printAll() 
CallBackとは、関数をパラメータとして関数に使用する方法です.しかし、このCalbackが多ければ多いほど、毒性はかなり低下します.

このようなcallback hellが発生すると、読むのが難しいだけでなく、修正するのも難しい.JavaScriptはpromiseという名前の作成者を使用してこの問題を解決することができます.

promise

	
const printString = (string) => {
    return new Promise((resolve, reject) => {
      setTimeout(
        () => {
         console.log(string)
         resolve()
        }, 
       Math.floor(Math.random() * 100) + 1
      )
    })
  }
 
  const printAll = () => {
    printString("A")
    .then(() => {
      return printString("B")
    })
    .then(() => {
      return printString("C")
    })
  }
  printAll()
以上の手順はcallbackで見たコードと同じです.promiseはresolveとacceptを受け入れて使用し、resolveはthenを使用して受信した関数をコールバックし、acceptはcatchを使用して受信した関数をコールバックする.

resolve reject

function buyAsync(money){
  return new Promise(function(resolve,reject){
    setTimeout(function(){
      let payment = parseInt(prompt("지불하고자 하는 금액을 입력하세요"));
      let balance = money-payment;
      if(balance>0){
        console.log(`${payment}원을 지불했습니다.`);
        resolve(balance);
      }else{
        reject(`잔액은 ${money}원 입니다. 구매 불가`);
      }
    },1000);
  });
}
buyAsync(500)
.then((balance)=>{
  console.log(`잔액은 ${balance}원 입니다.`);
  return buyAsync(balance);
})
.catch((error)=>{
  console.log(error);
});
resolve

reject

上記の結果が得られた.balance値が欠けている場合は拒否を実行し、保持されている場合は解析を実行します.その後、thenに含まれる関数はresolveにコールバックされ、catchに含まれる関数はexecuteにコールバックされる.

promise.all()

const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values);
});
promise.allは複数の入力時に使用されます.そして、1回の下痢行列が必要な場合には、複数を組み合わせて行列を作成するのではなくALL()を使用する.
promise1.then(p1=>{
    return promise3.then(p3=>{
        console.log(p1,promise2,p3)
    })
})
上のallを使わないとpromiseがcallbackを初めて使ったときのようにhellの形になっているのがわかります.

Async

function buyAsync(money){
  return new Promise(function(resolve,reject){
    setTimeout(function(){
      let payment = parseInt(prompt("지불하고자 하는 금액을 입력하세요"));
      let balance = money-payment;
      if(balance>0){
        console.log(`${payment}원을 지불했습니다.`);
        resolve(balance);
      }else{
        reject(`잔액은 ${money}원 입니다. 구매 불가`);
      }
    },1000);
  });
}

let result = async()=>{
    try{
        let money = await buyAsync(500);
        console.log(`잔액은 ${money}원 입니다.`);
    }catch(error){
        console.log(error)
    }
    
}
result();
AsyncはECMAScript 2017から本格的に追加された機能です.これをasync関数(){}にロードするか、async()=>{}にロードすることができます.awaitはasyncを使用して作成した関数に使用できます.tryは決意だと思って、catchは拒否だと思っています.awaitは戻り値をresolveの値とします.

fetch

var newsURL = 'http://localhost:5000/data/latestNews';
var weatherURL = 'http://localhost:5000/data/weather';

function getNewsAndWeatherAll() {
  // TODO: Promise.all을 이용해 작성합니다
  return Promise.all([
    fetch(newsURL).then(res => res.json()),
    fetch(weatherURL).then(res => res.json())
  ]).then(([newsData, weatherData]) => ({
    news: newsData.data,
    weather: weatherData
  }));
  // = .then(data=>{return {"news":data[0].data,"weather": data[1]};} 
}
getNewsAndWeatherAll().then(data => console.log(data));

if (typeof window === 'undefined') {
  module.exports = {
    getNewsAndWeatherAll
  }
}
fetchはurlにアクセスしてurlに必要な値を取得する関数です.

このurlはオブジェクトであり、ルイジンデータから構成されています.fetchを使用してデータを受信しpromiseとともに使用できます.

勉強するところ

  • fetchについてもっと詳しく議論しましょう.