async,await

11824 단어 자바 script
새 데이터 형식 심볼
특징.
  • new 생 성 을 사용 할 수 없습니다.let syml=Symbol('aaa')
  • 만 사용 할 수 있 습 니 다.
  • Symbol()이 되 돌아 오 는 것 이 유일한 값 입 니 다.
  • 단독 데이터 형식
  • symbol 이 key 일 때 for in 으로 순환 할 수 없습니다
  • 예시
    let syml = Symbol('aaa')
    
    // console.log(syml)
    
    let json = {
        'a': 'apple',
        'b': 'banana',
        [syml]: 'other'
    }
    
    // console.log(json[syml])
    
    for(let key in json){
        console.log(key)
    }
    

    promise
    특징.
  • Promise 는 비동기 프로 그래 밍 의 해결 방안 이다.
  • 은 쉽게 말 하면 으로 그 안에 어떤 미래 에 끝 날 수 있 는 사건(보통 )의 결과 가 보존 되 어 있다.
  • Promise 는 으로 이 가능 하 다.
  • 대상 의 상 태 는 외부의 영향 을 받 지 않 는 다.1.이 조작 비동기 작업 은 세 가지 상태 가 있 습 니 다.pending(진행 중),fulfilled(성공)과 rejected(실패)입 니 다.비동기 작업 의 결과 만 현재 어떤 상태 인지 결정 할 수 있 고 다른 작업 도 이 상 태 를 바 꿀 수 없습니다.프로 미스 라 는 이름 의 유래 이기 도 하 다.영어 로'약속'이라는 뜻 으로 다른 수단 으로 는 바 꿀 수 없다 는 뜻 이다.
  • 상태 가 바 뀌 면 다 시 는 변 하지 않 고 언제든지 이 결 과 를 얻 을 수 있다.Promise 대상 의 상태 변 화 는 두 가지 가능성 만 있다.pending 에서 fulfilled 으로,pending 에서 rejected 으로 바 뀔 수 있다.
  • resolve reject 는 하나만 실행 하고 함수
  • 입 니 다.
  • 실행 순 서 는 promise 의 함수-현재 대기 열 에서 동기 코드–then 중 코드
  • 을 먼저 실행 합 니 다.
  • promise 코드 는 오류 이 며,then 의 reject 방법 을 실행 하고,오류 메 시 지 를
  • 에 게 전달 합 니 다.
    async,await
    특징.
  • async 함수 Promise (한 방법 을 비동기 로 바 꾸 는 방법).
  • async 함수 내부 return then 방법 이 될 것 입 니 다.
  • await new promise() ; promise 를 실행 시 키 고 실 행 된 인 자 를 되 돌려 줍 니 다.
  • await 뒤의 비동기 코드 가 완성 되면 뒤의 코드
  • 을 실행 합 니 다.
  • await 는 문법 사탕 입 니 다.then 을 통과 하지 않 아 도 resolve 나 reject 의 매개 변 수 를 얻 을 수 있 습 니 다.
  • async 은 방법 을 변이 시 키 는 것 입 니 다.await 은 비동기 방법 이 실 행 될 때 까지 기다 리 는 것 입 니 다.비동기 방법 중의 데 이 터 를 얻 을 수 있 지만 비동기 방법 에서 사용 해 야 합 니 다.그리고 기능 을 막 을 수 있 습 니 다.비동기 로 전환 할 수 있 습 니 다*await 는 async 방법 에서 사용 해 야 합 니 다.예 1:
  •     async function gen(){
    
        //return               
    
        //       catch   
        // throw new Error('error')
        return '   ';
        }
    
    
        gen().then(res =>{ 
            console.log(res)
        }).catch(e=>{
            console.log(e)
        })
    

    예 2:
    
        let p = new Promise((resolve, reject)=>{
        resolve('success')
        })
    
        async function gen(){
            // await      promise             promise
            //    promise             
            let params = await p
            //  await           ,         
            console.log(params) //success
            //await          then     resolve reject   
            return params;
        }
    
    
        gen().then(res =>{ 
            console.log(res)
        }).catch(e=>{
            console.log(e)
        })
    
    

    generator
    특징.
  • 비동기 문 제 를 해결 하고 깊이 있 는 포 함 된
  • 구조 복제 let[a,b/...b]=gen()
  • 도 확장 연산 자
  • 을 사용 할 수 있 습 니 다.
  • Array.from( gen())

  • 예 1:
    function * gen(){
    
        
        yield '   '
        yield '   '
        return `   `
    }
    
    let g1 = gen();
    
    //   
    // console.log(g1.next()) //{ value: '   ', done: false }  false           
    // console.log(g1.next()) // { value: '   ', done: false }
    // console.log(g1.next()) // { value: '   ', done: true }
    
    // for of return       
    // for(let val of g1) {
    //     console.log(val)
    // }
    
    
    //    
    // let [a, b] = gen()
    // console.log(a)
    // console.log(b)
    
    
    //     
    //  yield       
    // let [...a] = gen()
    // console.log(a) //[ '   ', '   ' ]
    
    
    // console.log(Array.from(gen()))//[ '   ', '   ' ]
    

    예 2:
    const axios = require('axios')
    
    function * gen(username){
    
        let name ;
        name = yield username
        yield axios.get(`https://api.github.com/users/${name}`) //  name       
    }
    
    let g1 = gen('nianxiongdi')
    let username = g1.next().value
    // console.log(g1) { value: 'nianxiongdi', done: false }
    
    g1.next(username).value.then(resolve => {
        console.log(resolve.data.login)
    }).catch((e)=>{
        console.log(e)
    })
    // console.log( g1.next() )
    
    

    async,await,promise 사용 예
    1.async/await 함수
    const fetch = require('node-fetch')
    
    function getZhihuColumn(id) {
    
        const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
        fetch(url)
            .then(response => response.json()) //      json
            .then(data => {  
                // console.log(data)
    
                console.log("DES:" + `${data.description}`)
                console.log("INTRO:" + `${data.intro}`)
            })
    }
     
    getZhihuColumn('feweekly')
    

    2.async 함 수 를 promischiain 에 사용
    const fetch = require('node-fetch')
    
    //       
    //         ,  async await
    // async            promise           promise
    async function getZhihuColumn(id) {
    
        const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
        const response = await fetch(url) //          
        // const data = await response.json()
        // return data;
        
        //            
        return await response.json();
    }
    getZhihuColumn('feweekly')
        .then(data =>{
            console.log(`NAME: ${data.description}`)
            console.log("INTRO:" + `${data.intro}`)
        })
     
    

    3.임의의 종류의 함 수 를 async 스타일 로 변환
    
    const fetch = require('node-fetch')
    
    /*
                   async  
    */
    
    //       
    //        
    const getZhihuColumn = async (id) => {
    
        const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
        const response = await fetch(url) //          
        // const data = await response.json()
        // return data;
        
        //            
        return await response.json();
    }
    
    //  async            ,           ,       async
    (async () => {
        const data = await getZhihuColumn('feweekly');
        console.log(`NAME: ${data.description}`);
        console.log("INTRO:" + `${data.intro}`);
    })();
    
    
    const fetch = require('node-fetch')
    
    /*
                   async            
    */
     
    
    class APIClent {
        async getColumn(id) {
            const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
            const response = await fetch(url) //          
            return await response.json();
        }
    }
     
    //  async            ,           ,       async
    (async () => {
        const client = new APIClent();
        const data = await client.getColumn('feweekly'); //      await
        console.log(`NAME: ${data.description}`);
        console.log("INTRO:" + `${data.intro}`);
    })();
    
    
    
    

    4.async 처리 오류
    
    
    const fetch = require('node-fetch')
    
    /*
          async    
    */
    //       
    async function getZhihuColumn(id) {
    
        const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
        const response = await fetch(url) //          
    
        //      
        if(response.status !== 200){
            throw new Error(response.statusText)
        }
    
        return await response.json();
    }
    
    
    
    
     //  feweekly123   
    const showColumnInfo = async (id) =>{
        try {
            const data = await getZhihuColumn(id)
            console.log(`NAME: ${data.description}`)
            console.log("INTRO:" + `${data.intro}`)
        } catch (error) {
            console.log(error)
        }
    
    }
    
    showColumnInfo('feweekly123')
    /*
           , catch    
    Error: Not Found
        at getZhihuColumn (/home/nianxiongdi/Development/nodejs/es6/async/demo8.js:16:15)
        at process._tickCallback (internal/process/next_tick.js:68:7)
    */
    

    5.여러 await 작업 의 병렬 직렬 을 정확하게 처리 합 니 다.
    const fetch = require('node-fetch')
    
    /*
              await       
              
    */
    //       
    async function getZhihuColumn(id) {
    
        const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
        const response = await fetch(url) //          
    
        //      
        if(response.status !== 200){
            throw new Error(response.statusText)
        }
    
        return await response.json();
    }
    
    
     //  feweekly123   
    const showColumnInfo = async () =>{
        try {
            //     
            // const feweekly = await getZhihuColumn('feweekly')
            // const toolingtips = await getZhihuColumn('toolingtips')
    
            //    
            const feweeklyPromise = getZhihuColumn('feweekly')
            const toolingtipsPromise = getZhihuColumn('toolingtips')
            const feweekly = await feweeklyPromise;
            const toolingtips =await toolingtipsPromise;
    
            console.log(`NAME: ${feweekly.description}`)
            console.log("INTRO:" + `${feweekly.intro}`)
    
            console.log(`NAME: ${toolingtips.description}`)
            console.log("INTRO:" + `${toolingtips.intro}`)
    
    
        } catch (error) {
            console.log(error)
        }
    
    }
    
    showColumnInfo('feweekly123')
     
    

    6.promise.all()을 사용 하여 여러 await 작업 을 병행 합 니 다.
    
    
    const fetch = require('node-fetch')
    
    /*
          promise.all()   await     
              
    */
    //       
    async function getZhihuColumn(id) {
    
        const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
        const response = await fetch(url) //          
    
        //      
        if(response.status !== 200){
            throw new Error(response.statusText)
        }
    
        return await response.json();
    }
    
    
    
    
     //  feweekly123   
    const showColumnInfo = async () =>{
        try {
             //    
            //all()       promise       await
            const [feweekly, toolingtips ] = await Promise.all([
                getZhihuColumn('feweekly'),
                getZhihuColumn('toolingtips')
            ])
    
            console.log(`NAME: ${feweekly.description}`)
            console.log("INTRO:" + `${feweekly.intro}`)
    
            console.log(`NAME: ${toolingtips.description}`)
            console.log("INTRO:" + `${toolingtips.intro}`)
    
        } catch (error) {
            console.log(error)
        }
    
    }
    
    showColumnInfo('feweekly123')
     
    

    7.await 와 임의의 호 환.then()코드 를 결합
    const bluebird = require('bluebird')
    /**
     *   await     .then()   
     */
    
    async function main(){
    
        // const number = await 890;
        /**
         *  await    promise       promise
         *          
         * await Promise.resolve(890);
         */
        // console.log(number)
        await bluebird.delay(2000) //  2 
    }
    main()
    

    8.for 순환 에서 await 올 바 르 게 사용 하기
    
    const bluebird = require('bluebird')
    const fetch = require('node-fetch')
    
    /**
     *  for       await
     */
    
    async function getZhihuColumn(id) {
    
        // await bluebird.delay(1000);
    
        const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
        const response = await fetch(url) //          
    
        return await response.json();
    }
    
    
    const showColumnInfo = async () =>{
        try {
    
            console.time('showColumnInfo') //   
    
            const names = ['feweekly', 'toolingtips']
            /*
            //  1
            for(const name of names) {
                const data = await getZhihuColumn(name)
    
                console.log(`NAME: ${data.description}`)
                console.log("INTRO:" + `${data.intro}`)
            }
            */
    
            //   2
            const promises = names.map(x => getZhihuColumn(x));
            for(const promise of promises){
                const data = await promise
                console.log(`NAME: ${data.description}`)
                console.log("INTRO:" + `${data.intro}`)
            }
    
            console.timeEnd('showColumnInfo') //   
        } catch (error) {
            console.log(error)
        }
    }
    
    showColumnInfo()
    

    수식 기
  • 참조
  • https://www.npmjs.com/package/babel-plugin-transform-decorators-legacy
  • https://babeljs.io/docs/en/babel-plugin-proposal-decorators ...보완 해 야 할
  • 좋은 웹페이지 즐겨찾기