Error handling with async and await

Error handling with async and await

sync/await is the final solution to asynchrony based on Promise proposed by ES7.

To solve the problem of asynchronous callbacks in a real sense, the synchronous process expresses asynchronous operations. In essence, async is the syntactic sugar of Generator. Async and await are used to optimize the use of Generator, and there is no need to actively call next.

  1. There is no need to call the next method like Generator. When await waits, the current asynchronous operation is completed and executed.
  2. A function modified by async is an asynchronous function that always returns a Promise object, and the then method can be used for the next step.
  3. async replaces the asterisk * of the Generator function, await replaces the yield of the Generator
async function foo(){
    
    
	await 异步操作;
	await 异步操作;
}

foo(); // 注意: async函数, 总会返回一个Promise对象

Example: use setTimeout with Promise+async+await when defining asynchronous operations

1. Define a Promise function to perform asynchronous operations

function timeout(seconds) {
    
     // 延迟方法
	return new Promise(resolve => {
    
    
		setTimeout(resolve, seconds * 1000);
	})
}

2. Use async and await

async function asyncPrint(value) {
    
    
	console.log('函数执行---');
	await timeout(2);
	console.log('2秒后执行?');
	await timeout(4);
	console.log("4秒后执行?");
	console.log(value);
}
asyncPrint('hello async');

console.log("主线程代码----------");

When the expression following await returns a reject error message, await will not continue to execute downwards

If await is followed by a promise object, it will directly accept the result returned by resolve

await needs to be used with Promise objects;

Error reporting behavior:

        function timeout(seconds) {
    
     // 延迟方法
	        return new Promise((resolve,reject) => {
    
    
		    setTimeout(reject, seconds * 1000);
	        })
        }   

        const p = async ()=>{
    
    
        let aaa = await timeout(1)
        console.log(aaa)
        }
        p()

insert image description here
This kind of error uses await to report the error directly, which affects the subsequent aaa printing, which means that it affects the execution of the following code.
I also want to collect errors:
1. try/catch
2. Followed by a .catch()
3. Wrap a layer of promise processing

1.try/catch

        function timeout(seconds) {
    
     // 延迟方法
	        return new Promise((resolve,reject) => {
    
    
		    setTimeout(reject, seconds * 1000);
	        })
        }   

        const p = async ()=>{
    
    
            try{
    
    
                let aaa = await timeout(1)
                console.log(aaa)
            }catch{
    
    
                 console.log("error")
            }
        }
        p()

insert image description here

2. Followed by a .catch()

        function timeout(seconds) {
    
     // 延迟方法
	        return new Promise((resolve,reject) => {
    
    
		    setTimeout(reject, seconds * 1000);
	        })
        }   

        const p = async ()=>{
    
    
            let aaa = await timeout(1).catch(_=>'error')
            console.log(aaa)
        }
        p()

3. The outer packaging is a layer of promise processing

        const returnNewPro = (promise) => promise.then(res=>[null,res]).catch(err=>[err,null])
      
        function timeout(seconds) {
    
     // 延迟方法
	        return new Promise((resolve,reject) => {
    
    
		    setTimeout(reject, seconds * 1000);
	        })
        }   

        const p = async ()=>{
    
    
            let aaa = await returnNewPro(timeout(1))
            console.log(aaa)
        }
        p()

insert image description here
The above three methods are used to collect the error information of async/await to prevent the code from crashing.

Other articles

1. Hooks implement toDoList
2. Hooks implement left addition and right subtraction
3. React implements adding a multi-line input box (click a row to add a row)
4. React page jump cancels all requests on the previous page
5. React cooperates with axios request interception verification session, 403 jumps to the login page
6. Hooks use createStore, Provider, useSelector, useDispatch to implement the connect function
7. The problem of circular asynchrony in node ['solution']_Due to the map loop and for loop with async, Awaiting support
8. Promise asynchronous operation manager of js

Liuqing

见贤思齐焉,见不贤内自省

Personal opinion, please correct me if I am wrong.

Guess you like

Origin blog.csdn.net/qq_43291759/article/details/124022281