Difference between async/await and ES6 yield with generators

前端 未结 6 787
一个人的身影
一个人的身影 2021-01-30 00:03

I was just reading this fantastic article «Generators» and it clearly highlights this function, which is a helper function for handling generator functions:



        
6条回答
  •  感情败类
    2021-01-30 00:42

    Try this test programs which I used to understand await/async with promises.

    Program #1: without promises it doesn't run in sequence

    function functionA() {
        console.log('functionA called');
        setTimeout(function() {
            console.log('functionA timeout called');
            return 10;
        }, 15000);
    
    }
    
    function functionB(valueA) {
        console.log('functionB called');
        setTimeout(function() {
            console.log('functionB timeout called = ' + valueA);
            return 20 + valueA;
        }, 10000);
    }
    
    function functionC(valueA, valueB) {
    
        console.log('functionC called');
        setTimeout(function() {
            console.log('functionC timeout called = ' + valueA);
            return valueA + valueB;
        }, 10000);
    
    }
    
    async function executeAsyncTask() {
        const valueA = await functionA();
        const valueB = await functionB(valueA);
        return functionC(valueA, valueB);
    }
    console.log('program started');
    executeAsyncTask().then(function(response) {
        console.log('response called = ' + response);
    });
    console.log('program ended');
    

    Program #2: with promises

    function functionA() {
        return new Promise((resolve, reject) => {
            console.log('functionA called');
            setTimeout(function() {
                console.log('functionA timeout called');
                // return 10;
                return resolve(10);
            }, 15000);
        });   
    }
    
    function functionB(valueA) {
        return new Promise((resolve, reject) => {
            console.log('functionB called');
            setTimeout(function() {
                console.log('functionB timeout called = ' + valueA);
                return resolve(20 + valueA);
            }, 10000);
    
        });
    }
    
    function functionC(valueA, valueB) {
        return new Promise((resolve, reject) => {
            console.log('functionC called');
            setTimeout(function() {
                console.log('functionC timeout called = ' + valueA);
                return resolve(valueA + valueB);
            }, 10000);
    
        });
    }
    
    async function executeAsyncTask() {
        const valueA = await functionA();
        const valueB = await functionB(valueA);
        return functionC(valueA, valueB);
    }
    console.log('program started');
    executeAsyncTask().then(function(response) {
        console.log('response called = ' + response);
    });
    console.log('program ended');
    

提交回复
热议问题