亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home WeChat Applet WeChat Development Using async/await in WeChat development

Using async/await in WeChat development

Jun 06, 2020 pm 05:36 PM
WeChat applet

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() 就是一個封裝函數(shù),傳入原來的 wx.abcd 作為參加,返回一個 Promise 風格的新函數(shù)。代碼和解釋如下:

function promisify(fn) {
    // promisify() 返回的是一個函數(shù),
    // 這個函數(shù)跟傳入的 fn(即 wx.abcd) 簽名相同(或兼容)
    return async function(args) {
    //                    ^^^^ 接受一個單一參數(shù)對象
        return new Promise((resolve, reject) => {
    //             ^^^^^^^^^^^ 返回一個 Promise 對象
            fn({
    //      ^^ ^ 調(diào)用原函數(shù)并使用改造過的新的參數(shù)對象
                ...(args || {}),
    //          ^^^^^^^^        這個新參數(shù)對象得有原本傳入的參數(shù),
    //                      ^^  當然得兼容沒有傳入?yún)?shù)的情況
                success: res => resolve(res),
    //          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^  注入 success 回調(diào),resovle 它
                fail: err => reject(err)
    //          ^^^^^^^^^^^^^^^^^^^^^^^^ 注入 fail 回調(diào),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 回調(diào),
    // 因為 complete 的內(nèi)容可以寫在這里
}

2.2. 定義 wx.async()

不過老實說,把要用的異步方法通過 promisify 一個個處理,寫起來還是挺煩的,不如寫個工具函數(shù)把要用的方法一次性轉(zhuǎn)換出來。不過一查,wx 下定義了不知道多少異步方法,還是退而求其次,用到啥轉(zhuǎn)啥,不過可以批量轉(zhuǎn),轉(zhuǎn)出來的結(jié)果還是封裝在一個對象中。整個過程就是迭代處理,最后把每個處理結(jié)果聚焦在一起:

function toAsync(names) {    // 這里 names 期望是一個數(shù)組
    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({...});

有些人可能更習慣單個參數(shù)傳入的方式,像這樣

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

那么在 toAsync 的定義中,參數(shù)改為 ...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" 的這個數(shù)據(jù)不存在。

為什么原來沒有錯,現(xiàn)在卻報錯?

因為原來沒有定義 fail 回調(diào),所以錯誤被忽略了。但是 promisify() 把 fail 回調(diào)封裝成了 reject(),所以 awx.getStorage() 返回的 Promise 對象上,需要通過 catch() 來處理。我們沒有直接使用 Promise 對象,而是用的 await 語法,所以 reject() 會以拋出異常的形式體現(xiàn)出來。

用人話說,代碼得這樣改:

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

傷心了不是?如果沒有傷心,你想想,每一個調(diào)用都要用 try ... catch ... 代碼塊,還能不傷心嗎?

3.1. 忽略不需要處理的錯誤

處理錯誤真的是個好習慣,但真的不是所有錯誤情況都需要處理。其實要忽略錯誤也很簡單,直接在每個 Promise 形式的異步調(diào)后面加句話就行,比如

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

稍微解釋一下,在這里 awx.getStorage() 返回一個 Promise 對象,對該對象調(diào)用 .catch() 會封裝 reject 的情況,同時它會返回一個新的 Promise 對象,這個對象才是 await 等待的 Promise。

不過感覺 .catch(() => {}) 寫起來怪怪的,那就封裝成一個方法吧,這得改 Promise 類的原形

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

這段代碼放在定義 toAsync() 之前就好。

用起來也像那么回事

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

對于單個 await 異步調(diào)用,如果不想寫 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) {
    // 處理錯誤吧
}

看,不需要對每個異步調(diào)用定義?fail?回調(diào),一個?try ... catch ...?處理所有可能產(chǎn)生的錯誤,這可不也是 async/await 的優(yōu)勢!

推薦教程: 《微信小程序

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

Implement image filter effects in WeChat mini programs Implement image filter effects in WeChat mini programs Nov 21, 2023 pm 06:22 PM

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Implement image rotation effect in WeChat applet Implement image rotation effect in WeChat applet Nov 21, 2023 am 08:26 AM

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the &lt;swiper&gt; tag to achieve the switching effect of the carousel. In this component, you can pass b

Implement the sliding delete function in WeChat mini program Implement the sliding delete function in WeChat mini program Nov 21, 2023 pm 06:22 PM

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

See all articles