Home >WeChat Applet >Mini Program Development >Methods to implement synchronous requests in WeChat applet

Methods to implement synchronous requests in WeChat applet

不言
不言Original
2018-08-11 17:34:0916002browse

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,
  },
})

index.js

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

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
}

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!

Statement:
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