Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to gracefully catch the exception of asynchronous method in Mini Program

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you how to gracefully catch the exception of asynchronous method in Mini Program, I believe most people do not know much about it, so share this article for your reference. I hope you will learn a lot after reading this article. Let's take a look at it!

Traditional methods

After ES7, we often use async await syntax for asynchronous programming. If we want to catch exceptions, there are usually two ways

Try catch

Async func () {/ / do something} try {const res = await func ()} catch (error) {/ / handle error}

First of all, try catch catches exceptions. Using try catch is indeed very convenient to handle exceptions and prevent the following methods from being carried out, but in the process of development, we often have more than one asynchronous method, and using a lot of try catch is not only uncomfortable, but also definitely not elegant.

Promise.catch ()

Async func () {/ / do something} const res = await func () .catch (error= > {/ / handle error})

There is a try catch inside the Promise object, and we can use chained methods to handle exceptions. It's much better to write than try catch,Promise.catch (), and it looks more elegant.

But when we want to stop the execution of the method after catching the error, then Promise.catch () can't do it, as shown in the following example

Async func () {/ / do something} const res = await func (). Catch (error= > {/ / even return is not valid return}) / / if there is a mistake, I will not perform the elegant way.

Await-to-js github link

Https://github.com/scopsy/await-to-js

Await-to-js is a library that many people should know. It is a wrapper for asynchronous requests and can be used to handle errors in asynchronous requests. The example of using await-to-js according to our above requirements is as follows

Import to from 'await-to-js';async func () {/ / do something} const [err,res] = await to (func ()) if (err) {/ / handle error return} / / if there is an error, I will not execute it.

By using our asynchronous method as a parameter to the to () method, the return value is obtained by deconstructing an array, with the first value of the array being the caught error and the second value being the normally executed return value.

The implementation principle of await-to-js is also very simple, which is to use Promise.catch () to get the exception and then return the result in an array. The source code is as follows

Export function to (promise: Promise, errorExt?: object): Promise {return promise. Then (data: t) = > [null, data]. Catch ((err: U) = > {if (errorExt) {const parsedError = Object.assign ({}, err, errorExt); return [parsedError, undefined] } return [err, undefined];});} export default to; Mini Program

In Mini Program, we use the npm package is not convenient, so we can directly take out the source code to use alone, and then modify it, then we can elegantly carry out asynchronous programming, my own way of transformation is as follows.

/ / lib/awaitTo.jsmodule.exports = function to (promise Description= "unknown") {const pages = getCurrentPages () const route = pages [pages.length-1] .route | | 'unknown' description= `[${route}]-[${description}] `console.time (description) return promise .then (function (data) {console.timeEnd (description) return [null, data] ) .catch (function (err) {wx.showToast ({title: 'request failed', icon: "none"}) return [err, undefined] });}

I get the corresponding page route when the asynchronous method is executed through getCurrentPages (). When I change the second parameter to my own description of the asynchronous method, I output the execution time on the console each time the asynchronous method is called. Examples of practical use are as follows:

Const to = require (".. /.. / lib/awaitTo") const [err, res] = await to (db.collection ("post") .add ({data: form}), "addPost") if (err) {/ / handle my error return} / / logic executed after success

The execution time output of the console print is as follows, and the print format is

[routing page]-[method description]: execution time

These are all the contents of this article entitled "how to gracefully catch the exception of asynchronous methods in Mini Program". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report