Network request (2)

Callback

import Http from "../utils/Http";
import APIConfig from "../config/api";

class Service {
    
    

    /**
     *  分页获取服务列表
     * @param page
     * @param count
     * @param category_id 可以为null,
     * @param type
     */
    getServiceList(page, count, category_id = null, type = null) {
    
    
        console.log('获取服务列表')
        //发起网络请求,获取数据
        //统一的响应,异常处理
        const res = Http.request({
    
    url: 'v1/service/list', data: {
    
    page, count}},
            function (result) {
    
     //添加回调函数
                console.log(result)
            })
    }
}

Call the callback function and pass the result

	......
    static request({
    
    url, data, method = 'GET'},callBack) {
    
    
        wx.request({
    
    
            url:APIConfig.baseUrl+url,
            data,
            method,
            success:(result)=>{
    
    
                //全局统一响应、异常处理
                if (result.statusCode<400) {
    
    
                    callBack(result) //调用回调函数,回传结果
                }
                ......
            }
        })
    }
    ......

Promises solve callback hell

Rookie tutorial Promise learning: https://www.runoob.com/w3cnote/javascript-promise-object.html
Some native APIs of applets do not support Promise, among which wx.request() does not support and needs to be converted to Promise to solve Callback hell problem

Create a Promise-to-Promise tool in the utils folder in the tool folder:

export default function wxToPromise(method, options = {
     
     }) {
    
    
// resolve(解析)和 reject(拒绝)
    return new Promise((resolve, reject) => {
    
    
        options.success = resolve
        options.fail = err => {
    
    
            reject(err)
        }
        wx[method](options)
    })
}
  1. Use Promise to remove the callback event
import APIConfig from "../config/api";
import exceptionMessage from "../config/exception-message";
import wxToPromise from "./wx";

class Http {
    
    
    static request({
    
    url, data, method = 'GET'}) {
    
    

		//wxToPromise中的'requset'是wx.request中,request的方法名
        const res = wxToPromise('request', {
    
    
            url: APIConfig.baseUrl + url,
            data,
            method
        })
		//返回结果
        return res.then((result)=>{
    
    
            console.log(result)
            //全局统一响应、异常处理
            //请求成功
            if (result.statusCode < 400) {
    
    
                return result.data.data //直接返回结果
            }
            //请求失败
            if (result.statusCode === 401) {
    
    
                return
            }

            //打印错误信心
            Http._showError(result.data.error_code)
        })
    }
	......
}

export default Http
  1. View returned results
class Service {
    
    

    /**
     *  分页获取服务列表
     * @param page
     * @param count
     * @param category_id 可以为null,
     * @param type
     */
    getServiceList(page, count, category_id = null, type = null) {
    
    
        console.log('获取服务列表')
        //发起网络请求,获取数据
        //统一的响应,异常处理
       	//使用Promise直接返回结果
       	//返回了一个Promise对象
        const res = Http.request({
    
    url: 'v1/service/list', data: {
    
    page, count}})
        res.then(res1=>{
    
    
        	//取出结果
            console.log(res1) 
        })
    }
}

export default Service

Improve again, use async/await

  1. Add async and await to the method
class Http {
    
    
    static async request({
    
    url, data, method = 'GET'}) {
    
    

        const result = await wxToPromise('request', {
    
    
            url: APIConfig.baseUrl + url,
            data,
            method
        })

        //全局统一响应、异常处理
        //请求成功
        if (result.statusCode < 400) {
    
    
            return result.data.data //直接返回结果
        }
        //请求失败
        if (result.statusCode === 401) {
    
    
            return
        }

        //打印错误信心
        Http._showError(result.data.error_code)
    }
    ......
}
import Http from "../utils/Http";
import APIConfig from "../config/api";

class Service {
    
    
    /**
     *  分页获取服务列表
     * @param page
     * @param count
     * @param category_id 可以为null,
     * @param type
     */
    async getServiceList(page, count, category_id = null, type = null) {
    
    
        //发起网络请求,获取数据
        //统一的响应,异常处理
           // const res = await Http.request({url: "v1/service/list", data: {page, count}})
        // return res
        //直接返回不需要加await
        return Http.request({
    
    url: 'v1/service/list', data: {
    
    page, count}})
    }
}
export default Service
import Service from "../../model/service";

const service = new Service()
Page({
    
    
    data: {
    
    },
    onLoad: function (options) {
    
    
        this._getServiceList()
        // service.getToken()
    },

    //页面私有的函数,我们通常用下划线开头
    async _getServiceList() {
    
    
        //发起网络请求,获取服务列表的数据
        const serviceList = await service.getServiceList(1, 10)
        console.log('打印列表')
        console.log(serviceList)
    }
});

Example 2: Get classification data from the server

1. Create the model file category.js

class Category {
    
    
    static async getCategoryList() {
    
    
        return Http.request({
    
    
            url: 'v1/category'
        })
    }

    static async getCategoryListWithAll() {
    
    
        const categoryList = await Category.getCategoryList()
        //在list插入数据:全部
        categoryList.unshift({
    
    id: 0, name: '全部'})
        return categoryList
    }
}

export default Category

2. Use data

    onLoad: function (options) {
    
    
        this._getCategoryList()
    },

 	......

    async _getCategoryList() {
    
    
        const categoryList = await Category.getCategoryListWithAll()
        this.setData({
    
    
            categoryList:categoryList
        })
    },

Supongo que te gusta

Origin blog.csdn.net/xiaoduzi1991/article/details/120849660
Recomendado
Clasificación