Write a small program to tt. May be used when getUserInfo, tt. GetSystemInfo, tt) getSetting… All of these have one thing in common: they all have a callback function, and we use the results in SUCCESS. If you’re going to use more than one of these apis in your project, it’s better to do it all together, return the results with promises, avoid layers of callbacks, and keep your code clean
Premise: Use promise to wrap a function. If you haven’t already, check out my first article, which wraps wx.request() with promise; “(^_^)”
So let’s just look at the code process
First, you can put these utility functions in a file, such as utils.js
Function (obj = {}) {return (obj = {}) {return (obj = {}) {return (obj = {}) {return (obj = {}) {return (obj = {}) {return (obj = {}) New Promise((resolve, reject) => {obj = object. assign(obj, {success: res => {// 1, data: res }); }, fail: res => {// resolve({code: 0, data: res}); } }) api(obj); })} // Use const getUserInfo = promiseInit(tt.getUserInfo); const downLoadFile = promiseInit(tt.downLoadFile); module.exports = { getUserInfo, downLoadFile }Copy the code
The utils file is used to initialize the promise method, and then use the APIPromise. As long as conditions are met, we can promise, and then export it
Second, use it in the index.js file
Const utils = require('.. /.. /utils/util'); Page({data: {}, // Note that this is a promise function, so use onLoad with async and await: async function (options) { let result = await utils.getUserInfo(); Console. log(' user info ',result); }})Copy the code
{code: 1, data: {code: 1, data: {... }}// As expectedCopy the code
Please like and comment if it helps you
If there are mistakes, thank you for correcting oh ~
See you in the next article