Dealing with the problem of callback hell through promises, elementary

Dealing with the problem of callback hell through promises, elementary

What is the callback hell problem

I don’t know if you guys have used it to initiate a request to the interface through Ajax. If you have used it, you must have encountered such a problem, that is, use the ajax request in the ajax request, and then use the ajax request. If you use this operation many times, it will make your code particularly messy , make your own code look down on you, and it's easy to encounter errors.

Dealing with callback hell

The promise of ES6's new syntax can solve the problem of callback hell, go to the code! The setTimeOut here simulates asynchronous requests

new Promise((resolve, reject)=>{
	console.log('这是第一个数据')
	setTimeOut(()=>{
		resolve('这是第二个数据')
	},1000)
}).then(res=>{
	console.log(res);
	//如果想要继续回调函数,就需要返回一个新的promise对象
	return new Promise((resolve, reject){
		resolve('这是第三个数据')
	})
}).then(res=>{
	console.log(res);
}).catch(err=>{
	//此处的catch是获取上面所有的回调函数的异常,不止是最后一个
	console.log(err)
})

The final data result is to output "this is the first data" first, then output "this is the second data" after three seconds, and finally output "this is the third data", so it is through the promise processing method , The output result is the result of the output order you want.

Dealing with concurrency issues

If you need to get multiple requests, you can handle it through the Promise.all() method, and put all the requested data in an array.

Promise.all([
	new Promise((resolve, reject)=>{
		resolve('这是第一个数据');
	}),
	new Promise((resolve, reject)=>{
		resolve('这是第二个数据');
	})
]).then(res=>{
	console.log(res); //['这是第一个数据','这是第二个数据']
}).catch(err=>{
	console.log(err);
})

In this way, all the requested data is added to your res. Before, I wrote about how the generator handles the callback hell problem . Those who are interested, can take a look and comment.

Guess you like

Origin blog.csdn.net/iloveyu123/article/details/115282883