Home>Article>WeChat Applet> Using async/await in WeChat development

Using async/await in WeChat development

hzc
hzc forward
2020-06-06 17:36:37 2643browse

There are a large number of interfaces in WeChat mini programs that are asynchronous calls, such as wx.login(), wx.request(), wx.getUserInfo(), etc., which all use an object as a parameter and define success(), fail () and complete() serve as callbacks in different situations of asynchronous calls.

However, writing a program in the form of callbacks is really painful. If there is a process that needs to do these things in sequence:

  • wx.getStorage() Get the cache Data, check login status

  • wx.getSetting() Get configuration information,

  • wx.login() use configuration information to log in

  • wx.getUserInfo() Obtain user information after logging in

  • wx.request() Initiate a data request to the business server

Then, the code will probably look like this

wx.getStorage({ fail: () => { wx.getSetting({ success: settings => { wx.login({ success: ({ code }) => { wx.getUesrInfo({ code, success: (userInfo) => { wx.request({ success: () => { // do something } }); } }); } }); } }); } });

Obviously, async/await can make the code with the same logic look much more comfortable. However, by default, "WeChat Developer Tools" does not support async/await. How to enable?

1. Use async/await


If you are interested, search for async in the official WeChat applet documentation and you can find "Tools ⇒ Development Assistant ⇒ Code Compilation "The support for async/await is mentioned on the page. It is in a table in the "Add Compilation" section. There is an excerpt:

Development tools in 1.02.1904282 and later versions , an enhanced compilation option has been added to enhance the ability to convert ES6 to ES5. When enabled, new compilation logic will be used and additional options will be provided for developers to use.

  • Support async/await syntax, inject regeneratorRuntime on demand, the directory location is consistent with the auxiliary function

In short, That is, as long as the "WeChat Developer Tools" are updated to v1.02.1904282 or above, there is no need to do things like npm install regenerator. You only need to modify a configuration item to use the async/await feature. This configuration is in the "Toolbar⇒Details⇒Local Settings" page.

Using async/await in WeChat development

In order to quickly verify that async/await is available, add a piece of code to the onLaunch() event function of app.js:

(async () => { const p = await new Promise(resolve => { setTimeout(() => resolve("hello async/await"), 1000); }); console.log(p); })();

In a short period of automatic compilation After running, you can see the output in the Console tab of the debugger interface:

hello async/await

If not, please check the version of "WeChat Developer Tools" first - at least, downloading the latest version will not work. problematic.

2. Transform wx.abcd asynchronous method


Although async/await is supported, wx.abcd still needs to be modified () only needs to be encapsulated in Promise style.

Node.js provides promisify in the util module to convert Node.js style callbacks into Promise style, but obviously it does not work with wx style. Just do it yourself, and don’t think too much. For example, wx-style asynchronous calls are all consistent in form. Their characteristics are as follows:

  • Use an object to pass all parameters, including Three main callbacks

  • success: (res) => any Callback when the asynchronous method succeeds

  • ##fail: (err) = > any Callback when the asynchronous method fails

  • ##complete: () => any Callback when the asynchronous method completes (regardless of success or failure)
  • So, if wx.abcd() is changed to Promise style and written through async/await, it should probably look like this
try { const res = wx.abcd(); // do anything in success callback } catch (err) { // do anything in fail callback } finally { // do anything in complete callback }

Of course, the catch and finally parts are not Must, that is, do not necessarily have to use a try block. However, if catch is not used, there will be a pitfall, which will be discussed later. The first thing to do now is transformation.

2.1. Definition promisify()

promisify() 就是一个封装函数,传入原来的 wx.abcd 作为参加,返回一个 Promise 风格的新函数。代码和解释如下:

function promisify(fn) { // promisify() 返回的是一个函数, // 这个函数跟传入的 fn(即 wx.abcd) 签名相同(或兼容) return async function(args) { // ^^^^ 接受一个单一参数对象 return new Promise((resolve, reject) => { // ^^^^^^^^^^^ 返回一个 Promise 对象 fn({ // ^^ ^ 调用原函数并使用改造过的新的参数对象 ...(args || {}), // ^^^^^^^^ 这个新参数对象得有原本传入的参数, // ^^ 当然得兼容没有传入参数的情况 success: res => resolve(res), // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 注入 success 回调,resovle 它 fail: err => reject(err) // ^^^^^^^^^^^^^^^^^^^^^^^^ 注入 fail 回调,reject 它 }); }); }; }

举例使用它:

const asyncLogin = promisify(wx.login); // 注意别写成 wx.login(),为什么,我不说 try { const res = asyncLogin(); const code = res.code; // do something with code } catch (err) { // login error } finally { // promisify 里没有专门注入 complete 回调, // 因为 complete 的内容可以写在这里 }

2.2. 定义 wx.async()

不过老实说,把要用的异步方法通过 promisify 一个个处理,写起来还是挺烦的,不如写个工具函数把要用的方法一次性转换出来。不过一查,wx 下定义了不知道多少异步方法,还是退而求其次,用到啥转啥,不过可以批量转,转出来的结果还是封装在一个对象中。整个过程就是迭代处理,最后把每个处理结果聚焦在一起:

function toAsync(names) { // 这里 names 期望是一个数组 return (names || []) .map(name => ( { name, member: wx[name] } )) .filter(t => typeof t.member === "function") .reduce((r, t) => { r[t.name] = promisify(wx[t.name]); return r; }, {}); }

这个 toAsync 的用法大致是这样的

const awx = toAsync(["login", "request"]); await awx.login(); await awx.request({...});

有些人可能更习惯单个参数传入的方式,像这样

const awx = toAsync("login", "request");

那么在 toAsync 的定义中,参数改为 ...names 就好,即

function toAsync(...names) { ... }

还没完,因为我不想在每一个 JS 文件中去 import { toAsync } from ...。所以把它在 App.onLaunch() 中把它注入到 wx 对象中去,就像这样

App({ onLaunch: function() { // ... wx.async = toAsync; // ... } });

3. await 带来的神坑

工具准备好了,代码也大刀阔斧地进行了改造,看起来舒服多了,一运行却报错!为什么???

先来看一段原来的代码,是这样的

wx.getStorage({ key: "blabla", success: res => { // do with res } });

改造之后是这样

const res = await awx.getStorage({ key: "blabla" }); // <== runtime error // do with res

awx.getStorage 抛了个异常,原因是叫 "blabal" 的这个数据不存在。

为什么原来没有错,现在却报错?

因为原来没有定义 fail 回调,所以错误被忽略了。但是 promisify() 把 fail 回调封装成了 reject(),所以 awx.getStorage() 返回的 Promise 对象上,需要通过 catch() 来处理。我们没有直接使用 Promise 对象,而是用的 await 语法,所以 reject() 会以抛出异常的形式体现出来。

用人话说,代码得这样改:

try { const res = await awx.getStorage({ key: "blabla" }); // <== runtime error // do with res } catch (err) { // 我知道有错,就是当它不存在! }

伤心了不是?如果没有伤心,你想想,每一个调用都要用 try ... catch ... 代码块,还能不伤心吗?

3.1. 忽略不需要处理的错误

处理错误真的是个好习惯,但真的不是所有错误情况都需要处理。其实要忽略错误也很简单,直接在每个 Promise 形式的异步调后面加句话就行,比如

const res = await awx .getStorage({ key: "blabla" }) .catch(() => {}); // ^^^^^^^^^^^^^^^^ 捕捉错误,但什么也不干

稍微解释一下,在这里 awx.getStorage() 返回一个 Promise 对象,对该对象调用 .catch() 会封装 reject 的情况,同时它会返回一个新的 Promise 对象,这个对象才是 await 等待的 Promise。

不过感觉 .catch(() => {}) 写起来怪怪的,那就封装成一个方法吧,这得改 Promise 类的原形

Promise.prototype.ignoreError = function() { return this.catch(() => { }); };

这段代码放在定义 toAsync() 之前就好。

用起来也像那么回事

const res = await awx .getStorage({ key: "blabla" }) .ignoreError();

对于单个 await 异步调用,如果不想写 try ... catch ... 块,还可以自己定义一个 ifError(fn) 来处理错误的情况。但是如果需要批量处理错误,还是 try ... catch ... 用起顺手:

4. 回到开始

try { const storeValue = await awx.getStorage({}); const settings = await awx.getSetting(); const { code } = await awx.login(); const userInfo = await awx.getUserInfo({ code }); } catch (err) { // 处理错误吧 }

看,不需要对每个异步调用定义 fail 回调,一个 try ... catch ... 处理所有可能产生的错误,这可不也是 async/await 的优势!

推荐教程: 《微信小程序

The above is the detailed content of Using async/await in WeChat development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete