생성기 함수 JavaScript(Redux Saga 비동기 API 호출의 예 및 사용)

튜토리얼 로드맵


  • 생성기 함수 및 반복자?
  • 비동기 프로그래밍(Api 호출)에서의 사용

  • 생성기 함수 및 반복자



    A generator function is a function which allows us to control the execution of statements in it. i.e can be stopped mid way and continue from where it left



    예! yeild를 사용하여 언제든지 함수에서 값을 제거할 수 있으며 실행 중에 함수에서 일부 값을 전달할 수도 있습니다.
    yeild 'Anything' // returns anything and pauses
    명령문 흐름의 이러한 제어는 Iterators 객체에 의해 가능해집니다.

    반복자를 일반 영어로 표현하려면 다음과 같습니다.

    Process of looping over custom objects.



    알았어 위의 이론이 실제로 작동하는지 보자

    //Normal JS Function
    function myName(){
       //Statements
       return 'Danish Ali';
       return 'Unreachable statement';
    }
    
    const Name = myName();
    console.log(Name) // Danish Ali
    
    This is a working of normal function in JS, It runs till end following run to completion model.
    //This is generator function in work
    
    function* myNameGenerator(){
    
        yeild 'My'
        yeild 'Name is'
        yeild 'Danish'
        return 'Ali'
    
    }
    
    const nameGenerator = myNameGenerator
    console.log(nameGenerator) //{[Iterator]} 
    console.log(nameGenerator.next()) // {value:'My', done: false}
    

    Yes a generator function returns an Iterator (an Object)
    Iterator has an next method
    next() returns an object
    {value: Any, done: true | false}
    value is the next value from generator and done tells us if generator function is capable of generating more values. i.e when done is true there are no more values to be generated.



    //Continuing previous code...
    console.log(nameGenerator.next()) // {value:'Name is', done: false}
    console.log(nameGenerator.next()) // {value:'Danish', done: false}
    console.log(nameGenerator.next()) // {value:'Ali', done: true}
    

    At return statement the done is set to true, after that generators cannot further generate.




    다이어그램 : 일반 기능 대 생성기 기능

    비동기 프로그래밍에서의 사용(Api Calling)



    Redux용 미들웨어인 Redux Saga는 비동기성을 달성하기 위해 생성기가 제공하는 기능을 사용하여 개발되었습니다.
    Example of Generators used in redux saga
    function* loginRequest(obj) {
      //console.log('loginRequest Generator Function Called');
    
      const response = yield anyRequestFunction(data, 'Url');
    
      //console.log('Login Request Working', response);
    
      if (response.status === 200) {
        yield put(loginSuccess(response));
      } else if (response.status === 400) {
        yield put(loginFaliure(response));
      } else {
        yield put(loginFaliure(response));
      }
    }
    

    Here when api is called it pauses and executes in background while the control is transferred to next statement after generator call.



    끝까지 읽어 주셔서 감사합니다. 도움이 되었기를 바랍니다.
    행복한 코딩 :)


    유용한 링크
  • https://codeburst.io/understanding-generators-in-es6-javascript-with-examples-6728834016d5
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function
  • 좋은 웹페이지 즐겨찾기