How to elegantly catch exceptions in asynchronous methods in native applet? The following article will introduce to you the elegant use of async await asynchronous programming in small programs. I hope it will be helpful to you!
Recently I started writing an open source cloud development community applet. In the process of writing, I slowly explored some tricks that are helpful in the development and testing process. Yin Qiao. This article talks about how to elegantly catch exceptions from asynchronous methods innative applet.
After ES7, we often use theasync await
syntax for asynchronous programming. If we want to catch exceptions, there are generally two methods:
try catch
async func(){ //do something } try { const res = await func() } catch (error) { //handle error }
The first istry catch
to catch exceptions. It is really convenient to usetry catch
To handle exceptions, it can also prevent the subsequent methods from proceeding. However, during the development process, we often have more than one asynchronous method. Extensive use oftry catch
is not only unpleasant to write, but also definitely not elegant.
Promise.catch()
async func(){ //do something } const res = await func().catch(error=>{ //handle error })
Inside the Promise objecttry catch
, we can use chain calls method to handle exceptions. Compared withtry catch
,Promise.catch()
is certainly much easier to write and looks more elegant.
But when we want to stop the continued execution of the method after catching the error, thenPromise.catch()
There is no way to do it. The following example
async func(){ //do something } const res = await func().catch(error=>{ // 即使return也无效 return }) // 如果有错误的话我就不执行了
await-to-js github link
https://github.com/scopsy/await-to-js
await-to-js
This library should be familiar to many people. It is a wrapper for asynchronous requests. It can be used to handle errors in asynchronous requests. According to our above needs, it is modified to useawait-to- The example of js
is as follows
import to from 'await-to-js'; async func(){ //do something } const [err,res] = await to(func()) if(err){ //handle error return } // 如果有错误的话我就不执行了
By using our asynchronous method as the parameter of theto()
method, the return value is obtainedthroughan array destructuring, and the array No. One value is the caught error, and the second value is the return value from normal execution. The implementation principle of
await-to-js
is also very simple, that is, usePromise.catch()
to obtain the exception and then return the result in an array. The source code is as follows
export function to( promise: Promise , errorExt?: object ): Promise<[U, undefined] | [null, T]> { return promise .then<[null, T]>((data: T) => [null, data]) .catch<[U, undefined]>((err: U) => { if (errorExt) { const parsedError = Object.assign({}, err, errorExt); return [parsedError, undefined]; } return [err, undefined]; }); } export default to;
In small programs, it is not convenient for us to use npm packages, so we can directly take out the source code and use it alone, and then modify it. Asynchronous programming is done elegantly. My own transformation method is as follows.
// lib/awaitTo.js module.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: '请求失败', icon: "none" }) return [err, undefined]; }); }
I usedgetCurrentPages()
to get the corresponding page route when the asynchronous method is executed, and then changed the second parameter to my ownA description of the asynchronous method, every time an asynchronous method is called, the execution timewill be output on theconsole. Actual examples of use are as follows:
const to = require("../../lib/awaitTo") const [err, res] = await to(db.collection("post").add({ data: form }),"addPost") if (err) { // 处理我的错误 return } // 成功后执行的逻辑
The execution time output printed by the console is as follows, the printing format is
[Routing page]---[Method description]: Execution time
Of course, my encapsulation method is for my own code. You can also modify it according to your actual business, such as a unified entrance for buried points, etc. It can greatly improve development efficiency!
When using cloud development, you have to use native language to write for the development experience. The relatively closed environment makes many web-side methods unusable. In recent explorations I have also found many ways to improve the native applet development experience, which will be updated in the future.
[Related learning recommendations:小program development tutorial]
The above is the detailed content of How to elegantly catch exceptions in asynchronous methods in small programs. For more information, please follow other related articles on the PHP Chinese website!