Promise realizes alternate execution of red, green and yellow lights

During the interview, you can execute the cycle of red, yellow and green lights every second.

Seeing this problem, your first reaction I guess you may choose to use timer directly, the code is as follows:

function red() {
    
    
	console.log('red');
}
function green() {
    
    
	console.log('green');
}
function yellow() {
    
    
	console.log('yellow');
}
function index() {
    
    
	setTimeout(function() {
    
    
		red();
		setTimeout(function() {
    
    
			green();
			setTimeout(function() {
    
    
				yellow();
				setTimeout(function() {
    
    
					index();
				},0);
			},1000);
		},1000);
	},1000);
}
index();

If you are a beginner and you write this code, you may feel that you are awesome and very fulfilling, because the function is indeed realized. But when you have a bit of work experience, you will find, damn, this code was written by that stupid, so frustrated. Indeed, this code is highly coupled, and if the logic is complicated to change, it will be very troublesome. The code is also very readable, not conducive to debugging, and there is no idea of ​​function encapsulation. If you use this answer in the interview, the interviewer will definitely let you optimize the code, how to optimize using promises. Using promises you can write the following code:

	// 统一封装一个函数
	function light(fun, timer) {
    
    
        return new Promise((resolve, reject) => {
    
    
            setTimeout(() => {
    
    
                resolve(fun());
            }, timer);
        });
    }
    // 然后再调用
    function index() {
    
    
        light(red, 1000).then((data) => {
    
    
            return light(green, 1000);
        }).then((data) => {
    
    
            return light(yellow, 1000);
        }).then(() => {
    
    
            index();
        });
    }
    

After you implement this code, the interviewer will think that you are not bad, and the basic promises will still be used, but he may ask you, do you know async and await? Can you use async and await to achieve this function ? If you don’t understand the generator function, you probably won’t. Async and await are actually its syntactic sugar. Await is followed by a promise return object. The code is as follows

	function light(fun, timer) {
    
    
        return new Promise((resolve, reject) => {
    
    
            setTimeout(() => {
    
    
                resolve(fun());
            }, timer);
        });
    }
	async function index() {
    
    
        while(1) {
    
    
            await light(red, 1000);
            await light(green, 1000);
            await light(yellow, 1000);
        }
    }
	index();

Do you feel that this code is much more readable than the above, debugging is also convenient, and the code behind await must wait for it to return to execute the resolve() of the promise before it will continue to execute, making your code look like synchronous execution of.
Interested students can follow me to exchange and study together, and answer your questions for free. (The premise is that I can solve the front-end problem)

Guess you like

Origin blog.csdn.net/qq_42671194/article/details/108667100