preface

This is the third article in the ES6 series, and you can view all the previous articles here

The answers in this article are not necessarily optimal. If you have a better idea or a more elegant way to write it, please leave a comment

If there are flaws and mistakes in the article, please also see the small partners to give advice, thank you in advance

The following

The body of the

What does the following code output

let promise = new Promise((resolve, reject) = > {

    console.log(1)

    setTimeout((a)= > {

        resolve(2)

        console.log(3)

    }, 2000);

    reject('error')

})



promise

.then(res= > {

    console.log(5)

})

.catch(err= > {

    console.log(err)

})

Copy the code

The answer


1 error 3

Key points:

  • promiseIt is executed immediately after creation
  • Once the state changes, it doesn’t change againrejectresolveOnly one of them will be executed
  • The execution order of an asynchronous queue

The Js execution mechanism is recommended


What does the following code output

const first = (a)= > (new Promise((resolve,reject) = >{

    console.log(1);

    let p = new Promise((resolve, reject) = >{

         console.log(2);

        setTimeout((a)= >{

           console.log(3);

           resolve(4); 

        },0)

        resolve(5);

    }); 

    resolve(6);

    p.then((arg) = >{

        console.log(arg);

    });



}));



first().then((arg) = >{

    console.log(arg);

});

console.log(7);

Copy the code

The answer

One, two, seven, five, six, three

The same is true of promise and JS implementation

  • promiseCreate immediate execution, output in sequence1 2
  • Execute the synchronization task, output7
  • In the previous step, thep.thenAs well asfirst.thenJoin microtask execution queue, so output sequentially5 and 6
  • Finally, execute the macro tasksetTimeoutAnd the output3

What does the following code output

Promise.resolve(1)

.then(2)

.then(Promise.resolve(3))

.then(console.log)

Copy the code

The answer


1

  • If the parameter is a primitive value, or if it is one that does notthenMethod, thenPromise.resolveMethod returns a newPromiseObject whose state isresolved
  • thenA method takes a function as an argument, and if you pass something other than a function, it causes the previous onePromiseThe results penetrate down below

Why is it recommended to call the catch method at the end of a promise

The answer

First, let’s look at an example

Promise.resolve().then(res= > {

    throw new Error('error')

}, err => {

    console.log(err)

}).then(res= > {

    console.log(1)

})

Copy the code

In the above code, we throw an error in the THEN function and want to catch the error using the second argument in the THEN. Obviously, an error is thrown outside of the Promise function, bubbling up to the outermost layer as an uncaught error, since this is always the error from the previous Promise

Therefore, it is always recommended that a Promise object be followed by a catch method to handle errors that occur within the Promise

It’s important to note that the catch method also returns a new Promise object, so you can continue to use the Promise method, which also means that an error can occur in the catch method


Implement the mergePromise function, pass the array in order to execute, and return the data in the array data

const timeout = ms= > new Promise((resolve, reject) = > {

    setTimeout((a)= > {

        resolve();

    }, ms);

});



const ajax1 = (a)= > timeout(2000).then((a)= > {

    console.log('1');

    return 1;

});



const ajax2 = (a)= > timeout(1000).then((a)= > {

    console.log('2');

    return 2;

});



const ajax3 = (a)= > timeout(2000).then((a)= > {

    console.log('3');

    return 3;

});



const mergePromise = ajaxArray= > {

    // Implement your code here



};



mergePromise([ajax1, ajax2, ajax3]).then(data= > {

    console.log('done');

    console.log(data); // data 为 [1, 2, 3]

});



// Output is required separately

/ / 1

/ / 2

/ / 3

// done

/ / [1, 2, 3]

Copy the code

The answer

The main issue in this question is the control we use Promise for asynchronous operations

const mergePromise = ajaxArray= > {

    // Save the result of the array after the function is executed

    let data = []



    // Create a Promise object to control the asynchronous flow

    let p = Promise.resolve()



    // Iterate through the array in order to execute each item in the array

    // Save the result of each item in the array into a new array

    ajaxArray.forEach(item= > {

        p = p.then(item).then(res= > {

            data.push(res)

            return data

        })

    })



    // The final result: return a new Promise object

    // The result of return is passed as an argument in the next call to the THEN method

    return p

}

Copy the code


What does the following code output

functionfoo(x{

  var y = 2 * (yield (x + 1));

  var z = yield (y / 3);

  return (x + y + z);

}



let b = foo(5);

b.next()

b.next(15)

b.return('tadpole')

b.next(12)

Copy the code

The answer

// {value: 6, done: false}

// {value: 10, done: false}

// {value: 'tadpole', done: true}

// {value: undefined, done: true}

Copy the code
  • nextIs the value of the last expression
  • returnMethod that returns the given value and terminates the traversalGeneratorfunction

What does the following code output

async function async1({

    console.log("async1 start");

    await async2();

    console.log("async1 end");

    return 'async return';

}



async function async2({

    console.log("async2");

}



console.log("script start");



setTimeout(function({

    console.log("setTimeout");

}, 0);



async1().then(function (messageconsole.log(message) });



new Promise(function(resolve{

    console.log("promise1");

    resolve();

}).then(function({

    console.log("promise2");

});



console.log("script end")

Copy the code

The answer

// Execute the synchronization code and add it to the macro task queue when it encounters setTimeout

script start

/ / execution async1 ()

async1 start

/ / meet await execution release thread after the right expression, blocking code behind

async2

// Execute the synchronization code in the Promise to push the.then to the microtask queue

promise1

// Execute the synchronization code

script end

// Continue to execute the code after the await

// The async function returns a Promise object

// Add the.then following async1 to the microtask queue

async1 end

// Execute the code added to the microtask queue in the previous round

promise2

// The code for the next round of microtask queues

async return

// Start the next evenloop and execute the tasks in the macro task queue

setTimeout

Copy the code


The following requirements are implemented in different ways

// The red light is on once every three seconds, the green light is on once every two seconds and the yellow light is on once every second; How to keep three lights on alternately

/ / use Callback/Promise/Genertor/async respectively

// The light function is as follows



function red(){

    console.log('red');

}



function green(){

    console.log('green');

}



function yellow(){

    console.log('yellow');

}

Copy the code

The answer

// callback

function loop({

    setTimeout((a)= > {

        red()

        setTimeout((a)= > {

            green()

            setTimeout((a)= > {

                yellow()

                loop()

            }, 1000)

        }, 2000)

    }, 3000)

}

loop()



// Promise

function fn(timer, cb{

    return new Promise((resolve, reject) = > {

        setTimeout((a)= > {

            cb()

            resolve()

        }, timer);

    })

}



let promise = Promise.resolve()



function loop({

    promise.then(res= > {

        return fn(3000, red)

    }).then(res= > {

        return fn(2000, green)

    }).then(res= > {

        return fn(1000, yellow)

    }).then(res= > {

        loop()

    })

}



// Generator

function fn(timer, cb{

    return new Promise((resolve, reject) = > {

        setTimeout((a)= > {

            cb()

            resolve()

        }, timer)

    })

}



functiongen({

    yield fn(3000, red)

    yield fn(2000, green)

    yield fn(1000, yellow)

}



function loop(iterator, gen{

    // Execute the Generator function

    let result = iterator.next()



    if (result.done) {

        // We need to start again

        loop(gen(), gen)

    } else {

        result.value.then(res= > {

            loop(iterator, gen)

        })

    }

}



loop(gen(), gen)



// Async

function fn(timer, cb{

    return new Promise((resolve, reject) = > {

        setTimeout((a)= > {

            cb()

            resolve()

        }, timer)

    })

}



async function loop({

    while (true) {

        await fn(3000, red)

        await fn(2000, green)

        await fn(1000, yellow)

    }

}



loop()

Copy the code

Afterword.

This is all about ES6 in this installment, mainly involving Promise Generator and Async function related content, through several common interview questions and requirements to test the understanding of ES6 related knowledge

Leave a note, also hope to see the partner can be helpful

If you are interested, you can click here or scan the qr code below to follow my wechat official account for more information. Welcome to star

image

reference

ECMAScript introduction to 6

MDN

A JavaScript interview question that examines a variety of callbacks