微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

微信小程序中实现同步请求的方法

本篇文章给大家带来的内容是关于微信小程序中实现同步请求的方法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

微信小程序认是用同步请求的,但有些时候需要数据的同步请求,可使用的方法有很多,比较常用的有两种

1、 globalData 全局变量

app.js

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

index.js

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

2、 引用第三方库 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
}

相关推荐:

微信小程序实例:实现系统时间、时间戳时间以及时间戳加减的获取代码

微信小程序中多条数据缓存的代码实例

小程序组件:聊天会话组件的介绍(附代码)

原文地址:https://www.jb51.cc/weapp/1202059.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。