ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## :-: Promise回调,类式封装 ### 可修改式基础地址 ``` //config.js var config={ base_api_url:"http://douban.uieee.com/v2/" } export { config } ``` ### Promise封装HTTP ``` //utils/http.js import { config } from "../config"; class HTTP { request({url,method="GET",data={}}) { const promise = new Promise((resolve, reject) => { wx.request({ url: config.base_api_url + url, data, method, header: { 'Content-Type': 'json', }, success: (res=>{ const statusCode = res.statusCode.toString(); if (statusCode.startsWith("2")) { resolve(res.data); } else { this._show_error(); } }), fail: (err=> { reject(err); this._show_error(); }) }) }) return promise; } _show_error() { wx.showToast({ title: '网络错误', icon: 'none' }) } } export { HTTP }; ``` ### 继承类MovieModel再次封装,使用返回值,返回到promise ``` //models/movie.js import {HTTP} from "../utils/http"; class MovieModel extends HTTP{ getInTheaters(){ return this.request({ url:"in_theaters" }) } getTop250(){ return this.request({ url:"top250" }) } getComingSoon(){ return this.request({ url:"coming_soon" }) } } export {MovieModel}; ``` ### 页面调用HTTP,通过then关键字调用promise `Promise.all().then(res=>{})`,`res`会生成一个数组,需要用数组装载 ``` import {MovieModel} from "../../models/movie-p"; const movieModel = new MovieModel(); Page({ onLoad(){ 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); console.log(top250); console.log(comingSoon); }) } }) ```