1. 程式人生 > 其它 >把普通的函式回撥請求資料,變成Promise物件請求資料---小程式

把普通的函式回撥請求資料,變成Promise物件請求資料---小程式

1.純粹函式回撥請求資料特點

需要隨時傳遞迴調函式(把回撥函式當做引數傳入函式中)

2.純粹函式請求資料

2.1.在utils資料夾建立一個公共函式https.js

const commondata = getApp()
let statusCode = {
    '1': "網路出錯",
    "301": "永久重定向",
    "401": "登入出錯",
    "403": "被禁止訪問",
    "404": "找不到",
    "405": "錯誤請求方法",
    "409": "衝突",
    "413": "上傳檔案太大",
    "500": "伺服器錯誤"
    
}
// HTTP類 request函式:HTTP類的方法(類下面的函式稱為方法) class HTTP{ request(params){ if(!params.method){ params.method = "GET" } wx.request({ method: params.method, url: commondata.commonurl + params.url, data: params.data, header: {
"content-type": "application/json", "appkey": commondata.appkey }, success: (res) => { let code = res.statusCode.toString() if( code.startsWith("2") ){ // 當狀態碼是2開頭的情況 if(params.success){ params.success(res) } }
else{ // 當狀態碼不是2開頭的情況 this._showError(code) } }, fail: (err) => { // 當斷網的情況下,走fail函式 this._showError("1") } }) } // 封裝錯誤彈框型別 _showError(code){ wx.showToast({ "title": statusCode[code] ? statusCode[code] : statusCode[1], "icon": "error", "duration": 1500 }) } } export { HTTP }

2.2.再建立一個model模組,建立classic.js檔案,在classic.js檔案中呼叫http.js公共函式

import { HTTP } from "../utils/https"

class classModel extends HTTP {
    getLatest(thecallback){
        this.request({
            url: "classic/latest",
            success: (res) => {
                thecallback(res)
            }
        })
    }
    gettheOthers(index, directions, thecallback){
        this.request({
            url: `classic/${index}/${directions}`,
            success: (res) => {
                thecallback(res)
            }
        })
    }
    getnewestBoolen(index){
        return index == 8  ? true : false
    }
    getfirstBoolen(index){
        return index == 1 ? true : false
    }
    _tosetNewestIndexStotrage(index){
        wx.setStorageSync("newestIndex", index)
    }
    _togetNewestIndexStotrage(){
        wx.getStorageSync("newestIndex")
    }
    _classicStroageIndex(index){
        return "class_" + index
    }
}

export { classModel }

2.3.在classic的page頁面中呼叫model模組中的classic.js檔案,具體實施請求資料的動作。

3.Promise物件請求資料

3.1.在utils資料夾建立一個公共函式https-p.js

const commondata = getApp()
let statusCode = {
    '1': "網路出錯",
    "301": "永久重定向",
    "401": "登入出錯",
    "403": "被禁止訪問",
    "404": "找不到",
    "405": "錯誤請求方法",
    "409": "衝突",
    "413": "上傳檔案太大",
    "500": "伺服器錯誤"
    
}
// HTTP類    request函式:HTTP類的方法(類下面的函式稱為方法)
class HTTP{
    request({url, data={}, method="GET"}){
        let thepromise = new Promise( (resolve, reject) => {
            this._request(url, resolve, reject, data, method)
        })
        return thepromise
    }

    _request(url, resolve, reject, data={},  method="GET"){
        wx.request({
            method: method,
            url: commondata.commonurl + url,
            data: data,
            header: {
                "content-type": "application/json",
                "appkey": commondata.appkey
            },
            success: (res) => {
                let code = res.statusCode.toString()
                if( code.startsWith("2") ){
                    // 當狀態碼是2開頭的情況
                    resolve(res)
                }else{
                    reject()
                    // 當狀態碼不是2開頭的情況
                    this._showError(code)
                }
            },
            fail: (err) => {
                reject()
                // 當斷網的情況下,走fail函式
                this._showError("1")
            }
        })
    }

    // 封裝錯誤彈框型別
    _showError(code){
        wx.showToast({
            "title": statusCode[code] ? statusCode[code] : statusCode[1],
            "icon": "error",
            "duration": 1500
        })
    }
}

export { HTTP }

3.2.在model模組中,建立book.js檔案,在book.js檔案中呼叫http-p.js公共函式

import { HTTP } from "../utils/https-p.js"

class bookModel extends HTTP {
    getHostList(){
        return this.request({
            url: "book"
        })
    }
}

export { bookModel }

3.3.在book的page頁面中呼叫model模組中的book.js檔案,具體實施請求資料的動作。

 

4.Promise物件解決了回撥地域的缺陷

請求函式getHotList成功之後,需要在getHotList請求成功的前提下,再一次請求getMyBookCount。

請求函式getMyBookCount成功之後,需要在getMyBookCount請求成功的前提下,再一次請求getMyBookCount。

即,請求函式一環套一環,這就是俗稱的“回撥地域”。

用Promise物件後,可以通過以下的then的方式來很好的展示出來。

 Tips:通過在then方法裡面使用return來返回promise物件,然後就可以繼續下一次請求函式時候再次的使用then方法。