溫馨提示×

溫馨提示×

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

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

微信小程序如何實現(xiàn)異步API為Promise簡化異步編程

發(fā)布時間:2021-07-06 10:17:29 來源:億速云 閱讀:240 作者:小新 欄目:web開發(fā)

這篇文章主要介紹了微信小程序如何實現(xiàn)異步API為Promise簡化異步編程,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

把微信小程序異步API轉(zhuǎn)化為Promise。用Promise處理異步操作有多方便,誰用誰知道。

微信官方?jīng)]有給出Promise API來處理異步操作,而官方API異步的又非常多,這使得多異步編程會層層回調(diào),代碼一復雜,回調(diào)起來就想砸電腦。

于是寫了一個通用工具,把微信官方的異步API轉(zhuǎn)化為Promise,方便處理(多)異步操作。

你可以這樣用:

準備轉(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 其他你項目中可能用到的異步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(() => {
    //保存失敗
   })
 }
})

項目地址:to-promise

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

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

優(yōu)點:

避免小程序異步編程多次回調(diào)帶來的過多回調(diào)導致邏輯不清晰,篇幅過長等問題。
借助于Promise異步編程特點,支持鏈式操作,像同步一樣寫異步。
轉(zhuǎn)化后得API幾乎和微信官方API一樣。

使用方法:

安裝

使用git安裝到項目根目錄/module,

git clone https://github.com/tornoda/to-promise
或直接下載放入項目目錄下如:/module
在需要用到的地方引入
import toPromise from '/module/to-promise/src/index'
綁定微信全局對象(wx)到函數(shù),以便可以取到微信得API
const toPromiseWx = toPromise(wx)
開始轉(zhuǎn)化你需要得異步API
//apiName為微信異步方法名,如對wx.request()進行轉(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)//控制臺打印storage中key對于的value
   return res.data//如果需要繼續(xù)鏈式調(diào)用轉(zhuǎn)化后的api,需要把值顯示返回
  },
  (err) => {
   //err的值與wx.getStorage({ success: (err) => {} })中的err值一樣
   throw err
  }
 )

關(guān)于Promise對象的使用,請參見Promise

API

toPromise(global)

參數(shù)

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

返回

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

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

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

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

簡單點來說,

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)用等價

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)用場景舉例

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

  • 多次異步操作調(diào)用,且每下一次調(diào)用都會用到前一次返回的結(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')
//鏈式寫邏輯
getLocation() //獲取位置信息
 .then(
  (res) => { //位置獲取成功后的處理,res為返回信息
   //處理res后返回有用的信息,這里直接返回res,用于演示
   return Promise.resolve(res) //必須
  },
  (err) => { //位置獲取失敗后的錯誤處理,err為錯誤信息
   //錯誤處理
   return Promise.resolve(err) //必須
  }
 )
 .then(
  (res) => { //根據(jù)位置獲取成功后的信息,請求天氣信息
   return request({ url: 'http://api.weather.com'}) //返回一個pending 狀態(tài)下的Promise
  }
 )
 .then(
  (res) => { //天氣獲取成功后存入storage的回調(diào)
   setStorage({
    key: 'test',
    data: 'res'
   })
  },
  (err) => {
   //天氣獲取失敗后執(zhí)行這里,err為獲取天氣失敗的錯誤信息
  }
 )

如果使用官方的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),如果邏輯再復雜點,可能就瘋了

感謝你能夠認真閱讀完這篇文章,希望小編分享的“微信小程序如何實現(xiàn)異步API為Promise簡化異步編程”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!

向AI問一下細節(jié)

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

AI