I have tried both Promise and co, but finally I couldn’t help but come up with the ultimate solution for ES7: async/await.
async/await is also used in conjunction with Promise. Let’s take a look at the sample code first. This usage is very similar to the co usage we talked about before:
function myAsyncFunc() { return new Promise(function (resolve, reject) { setTimeout(function () { console.log("myAsyncFunction done!"); resolve({data: "Hello,World"}); }, 5000); }); } async function test() { var result = await myAsyncFunc(); console.log(result.data); //Hello,World } test();
To be used in a small program If you use async/await, it is not enough to rely on the Babel conversion tool in WeChat web developer tools, because some additional Babel plug-ins are needed to compile the code using async/await. So this time we have to write our own script to call Babel.
In the project, we have to turn off the "Turn on ES6 to ES5" option first, because we now have to do this ourselves.
Then, I am going to use Gulp to write my script and call Babel from Gulp to compile my code. Of course, you can also use your other tools such as Grunt, Webpack, etc. You can refer here to learn how to use Babel in the build tool you use.
The important point is that when we call Babel, we need to configure plug-ins for our Babel to support async/await, such as async-to-generator, async-generator-functions and other plug-ins. For convenience, use the preset directly (that is, the officially configured plug-in package). One of the two presets, es2017 or latest, can meet our needs.
This is Babel’s configuration file: .babelrc
{ "presets": [ "latest" ], "plugins": [] }
Then in my gulpfile.js, I will compile all js files under my mini program project through Babel:
gulp.task('scripts', () => { return gulp.src('./src/**/*.js') .pipe(babel()) .pipe(gulp.dest('./dist')) })
Okay, this is what we have to do to compile our code. Next, let’s talk about some changes to be made in the mini program code:
The code translated by Babel will pass the aysnc/await function It is implemented in a way similar to the co library, that is, using a generator. Therefore, just like when we use co, we need to rely on a regeneratorRuntime to support the generator feature. We can use Facebook's open source regenerator library. You can download this regenerator library through npm:
npm install regenerator
Then take out the file named regenerator-runtime.js in the downloaded file and put it into our applet code.
Introduce the regenerator library into the code file that needs to use the async/await feature:
const regeneratorRuntime = require('../../libs/regenerator-runtime')
Then, you can rest assured in your code Here we use async/await to write asynchronous processing.
The above is the detailed content of Detailed explanation of asynchronous processing examples in WeChat applet (async/await). For more information, please follow other related articles on the PHP Chinese website!