溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么把微信小程序異步API為Promise

發(fā)布時(shí)間:2022-03-11 10:47:09 來源:億速云 閱讀:220 作者:iii 欄目:開發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“怎么把微信小程序異步API為Promise”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“怎么把微信小程序異步API為Promise”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

準(zhǔn)備轉(zhuǎn)化后的方法并暴露出

// /utils/wx-promise.js
import toPromise from '/module/to-promise/src/index'

const toPromiseWx = toPromsie(wx)

export const request = toPromiseWx('requset')
export const getLocation = toPromiseWx('getLocation')
export const setStorage = toPromiseWx('setStorage')

//export 其他你項(xiàng)目中可能用到的異步API

在其他文件中使用
在App.js中使用:

//App.js
import { request } from './utils/wx-promise.js'

App({
  onLanuch: () => {
    request({ url: 'http://api.yourapi.com' })
      .then(() => {
        //成功后處理
      })
      .then(() => {
        //失敗后處理
      })
  }
})

在其他page中使用:

// /page/index.js
import { request, setStorage } from '../utils/wx-promise.js'

page({
  onLoad: () => {
    request({ url: 'http://api.yourapi.com' })
      .then(() => {
        //成功后處理
      })
      .then(() => {
        //失敗后處理
      })
  },
  onHide: () => {
    setStorage({
      key: 'yourkey',
      data: 'yourvalue'
    })
      .then(() => {
        //保存成功
      })
      .then(() => {
        //保存失敗
      })
  }
})

項(xiàng)目地址:to-promise

其他更多更具體用法,直接粘貼README了,如下。


to-promise是一個(gè)轉(zhuǎn)換微信小程序異步API為Promise的一個(gè)工具庫

優(yōu)點(diǎn):

  1. 避免小程序異步編程多次回調(diào)帶來的過多回調(diào)導(dǎo)致邏輯不清晰,篇幅過長等問題。

  2. 借助于Promise異步編程特點(diǎn),支持鏈?zhǔn)讲僮?,像同步一樣寫異步?/p>

  3. 轉(zhuǎn)化后得API幾乎和微信官方API一樣。

使用方法:

  1. 安裝

  • 使用git安裝到項(xiàng)目根目錄/module,

git clone https://github.com/tornoda/to-promise
  • 或直接下載放入項(xiàng)目目錄下如:/module

  1. 在需要用到的地方引入

import toPromise from '/module/to-promise/src/index'
  1. 綁定微信全局對(duì)象(wx)到函數(shù),以便可以取到微信得API

const toPromiseWx = toPromise(wx)
  1. 開始轉(zhuǎn)化你需要得異步API

//apiName為微信異步方法名,如對(duì)wx.request()進(jìn)行轉(zhuǎn)化
const request = toPromiseWx('request')
//直接使用request方法

舉例:

import toPromise from '/module/to-promise/src/index'

//轉(zhuǎn)換wx.getStorage()
const getStorage = toPromsie(wx)('getStorage') 

//使用
getStorage({ key: 'test' })
  .then(
    (res) => {
      //res的值與wx.getStorage({ success: (res) => {} })中的res值一樣
      //res = {data: 'keyValue'}
      console.log(res.data)//控制臺(tái)打印storage中key對(duì)于的value
      return res.data//如果需要繼續(xù)鏈?zhǔn)秸{(diào)用轉(zhuǎn)化后的api,需要把值顯示返回
    },
    (err) => {
      //err的值與wx.getStorage({ success: (err) => {} })中的err值一樣
      throw err
    }
  )

關(guān)于Promise對(duì)象的使用,請(qǐng)參見Promise

API

  • toPromise(global)

參數(shù)

(wx): wx全局對(duì)象。即toPromise(wx)這樣調(diào)用

返回

(function): 參數(shù)(string)為小程序異步方法名。返回一個(gè)函數(shù),該函數(shù)的參數(shù)與返回值如下。

參數(shù):(object) 對(duì)應(yīng)wx小程序異步方法中的參數(shù)(OBJECT)除去success與fail后的對(duì)象。例如:

官方APIwx.getLocation(OBJECT)的OBJECT接受如下屬性: type altitude success fail complete,那么去除(success fail)后為:type altitude complete。

返回: (pending Promsise) 返回一個(gè)未知狀態(tài)的Promise對(duì)象,在該對(duì)象上調(diào)用.then(onFulfilled, onRejected)方法來處理對(duì)用成功或失敗的情況。onFulfilled為請(qǐng)求成功后調(diào)用的回調(diào)函數(shù),參數(shù)為返回值,onRejected為請(qǐng)求失敗后的回調(diào)函數(shù),參數(shù)為返回的錯(cuò)誤信息。

簡單點(diǎn)來說,

const getLocation = toPromiseWx('getLocation')
getLocation({
  type: 'wgs84',
  altitude: true,
  complete: () => { console.log('to-promsise is awesome') }
}).then(
  (res) => {//dosomething if succeed},
  (err) => {//dosomething if failed}
)

與下面官方調(diào)用等價(jià)

wx.getLocation({
  type: 'wgs84',
  altitude: true,
  complete: () => { console.log('to-promsise is awesome') },
  success: (res) => {//dosomething if succeed},
  fail: (err) => {//dosomething if failed}
})

應(yīng)用場(chǎng)景舉例

  1. 單次異步調(diào)用,參見API最后

  2. 多次異步操作調(diào)用,且每下一次調(diào)用都會(huì)用到前一次返回的結(jié)果。
    如:獲得GPS信息后,根據(jù)GPS信息獲取天氣信息,取得天氣信息后立馬存入localStorage。

import toPromise from '/module/to-promise/src/index'

const toPromiseWx = toPrmise(wx)

//方法轉(zhuǎn)換
const getLocation = toPromiseWx('getLocation')
const request = toPromiseWx('request')
const setStorage = toPromiseWx('setStorage')

//鏈?zhǔn)綄戇壿?
getLocation() //獲取位置信息
  .then(
    (res) => { //位置獲取成功后的處理,res為返回信息
      //處理res后返回有用的信息,這里直接返回res,用于演示
      return Promise.resolve(res) //必須
    },
    (err) => { //位置獲取失敗后的錯(cuò)誤處理,err為錯(cuò)誤信息
      //錯(cuò)誤處理
      return Promise.resolve(err) //必須
    }
  )
  .then(
    (res) => { //根據(jù)位置獲取成功后的信息,請(qǐng)求天氣信息
      return request({ url: 'http://api.weather.com'}) //返回一個(gè)pending 狀態(tài)下的Promise
    }
  )
  .then(
    (res) => {  //天氣獲取成功后存入storage的回調(diào)
      setStorage({
        key: 'test',
        data: 'res'
      })
    },
    (err) => {
      //天氣獲取失敗后執(zhí)行這里,err為獲取天氣失敗的錯(cuò)誤信息
    }
  )

如果使用官方的API寫上述邏輯,代碼是這樣的:

wx.getLocation({
  success: (res) => {
    //some transformation with res
    wx.request({
      url: 'http://api.weather.com',
      success: (res) => {
        wx.setStorage({
          success: () => {
            //do something
          },
          fail: (err) => {
            //do something if err happend
          }
        })
      },
      fail: (err) => {
        //do something if err happend
      }
    })
  },
  fail: (err) => {
    //do something if err happend
})
//層層回調(diào),如果邏輯再復(fù)雜點(diǎn),可能就瘋了

讀到這里,這篇“怎么把微信小程序異步API為Promise”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI