微信小程序基于Promise的HTTP请求封装与使用示例

作者:纸飞机

时间:2026-10-23

浏览:530

本文详细介绍微信小程序中如何封装基于Promise的HTTP请求类,并通过MovieModel示例展示如何调用豆瓣API获取电影数据。文章提供了完整的config.js、http.js及页面调用代码,帮助开发者实现高效的异步网络请求处理。

文章目录

微信小程序Promise封装概述

本文主要介绍了微信小程序前端中Promise封装的具体代码实现。文中通过详细的示例代码进行了深入解析,对读者的学习或实际工作具有一定的参考和学习价值,有需要的朋友可以参考以下内容。

具体的实现代码如下所示:

基础配置与网络请求封装

配置文件 config.js 的内容如下:


const config = {
   base_url_api : "https://douban.uieee.com/v2/movie/",
}

export {config}

网络请求封装类 http.js 的实现代码如下:


import { config } from "../config";
class HTTP {
  requset({ url, method = "GET", data = {} }) {
    const promise = new Promise((resolve, reject) => {
      wx.request({
        url: config.base_url_api + url,
        data,
        method,
        header: {
          'Content-Type': 'json'
        },
        success: res => {
          //状态码 toString() 转成字符串
          const statusCode = res.statusCode.toString();

          if (statusCode.startsWith("2")) {
            resolve(res.data)
          } else {
            this._show_error();
          }
        },
        fail: res => {
          reject(err);
          this._show_error();
        }
      })
    })
    return promise;
  }
  _show_error() {
    wx.showToast({
      title: '网络错误',
      icon: 'none'
    })
  }
}
export { HTTP }

数据模型与页面调用示例

电影数据模型 model/movie.js 的定义如下:


import {HTTP} from "../utils/http";
class MovieModel extends HTTP{
  getInTheaters(){
    return this.requset({
      url:"in_theaters"
    })
  }
  getTop250(){
    return this.requset({
      url:"top250"
    })
  }
  getComingSoon(){
    return this.requset({
      url:"coming_soon"
    })
  }
}
export {MovieModel};

页面 index.js 中调用上述模型的示例代码如下:


const app = getApp();
import {MovieModel} from "../../model/movie";
const movieModel = new MovieModel();
Page({
 onLoad(){
  // movieModel.getInTheaters().then(res=>{
  //  console.log(res)
  // })
  const inTheaters = movieModel.getInTheaters()
  const top250 = movieModel.getTop250();
  const comingSoon = movieModel.getComingSoon();
  Promise.all([inTheaters,top250,comingSoon]).then(res=>{
   let[inTheaters,top250,comingSoon] = res;
   console.log(inTheaters)
  })
 }
})

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章