Methods to implement synchronous requests in WeChat applet

不言
Release: 2018-08-11 17:34:09
Original
15949 people have browsed it

The content of this article is about the method of implementing synchronous requests in WeChat applet. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The WeChat applet uses synchronous requests by default, but sometimes synchronous requests for data are required. There are many methods that can be used, and there are two commonly used ones

1. globalData Global variables

app.js

App({
  // 全局变量
  globalData: {
    currentPage: 1,
    allData: null,
    findData: null,
  },
})
Copy after login

index.js

// 获取应用实例
const app = getApp();
// 使用全局变量
data = app.globalData.currentPage;
Copy after login

2. Reference third-party library es6-promise

var Promise = require('../plugins/es6-promise.js')

function wxPromisify(fn) {
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        //成功
        resolve(res)
      }
      obj.fail = function (res) {
        //失败
        reject(res)
      }
      fn(obj)
    })
  }
}
//无论promise对象最后状态如何都会执行
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};
/**
 * 微信请求get方法
 * url
 * data 以对象的格式传入
 */
function getRequest(url, data) {
  var getRequest = wxPromisify(wx.request)
  return getRequest({
    url: url,
    method: 'GET',
    data: data,
    header: {
      'Content-Type': 'application/json'
    }
  })
}

/**
 * 微信请求post方法封装
 * url
 * data 以对象的格式传入
 */
function postRequest(url, data) {
  var postRequest = wxPromisify(wx.request)
  return postRequest({
    url: url,
    method: 'POST',
    data: data,
    header: {
      "content-type": "application/x-www-form-urlencoded"
    },
  })
}

module.exports = {
  postRequest: postRequest,
  getRequest: getRequest
}
Copy after login

Related recommendations:

Example of WeChat applet: code for obtaining system time, timestamp time, and timestamp addition and subtraction

Code example for caching multiple pieces of data in WeChat applet

Mini Program Component: Introduction to Chat Session Component (with code)

The above is the detailed content of Methods to implement synchronous requests in WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template