搜尋
首頁微信小程式小程式開發微信小程式Promise簡化回呼實例分享

微信小程式Promise簡化回呼實例分享

May 15, 2018 pm 05:09 PM
promise分享小程式

Promise 是非同步程式設計的一種解決方案,比傳統的解決方案——回呼函數和事件——更合理和更強大。它由社群最早提出和實現,ES6 將其寫進了語言標準,統一了用法,原生提供Promise物件。本文主要跟大家介紹微信小程式使用Promise簡化回調,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟著小編過來看看吧,希望能幫助大家。

所謂Promise,簡單說就是一個容器,裡面保存著某個未來才會結束的事件(通常是一個非同步操作)的結果。從語法上說,Promise 是一個對象,從它可以獲取非同步操作的訊息。 Promise 提供統一的 API,各種非同步操作都可以用同樣的方法處理。

了解什麼是 Promise 物件

在專案中,會出現各種非同步操作,如果一個非同步操作的回呼裡還有非同步操作,就會出現回呼金字塔。

例如下面這種

// 模拟获取code,然后将code传给后台,成功后获取userinfo,再将userinfo传给后台
// 登录
wx.login({
  success: res => {
    let code = res.code
    // 请求
    imitationPost({
      url: '/test/loginWithCode',
      data: {
        code
      },
      success: data => {
        // 获取userInfo
        wx.getUserInfo({
          success: res => {
            let userInfo = res.userInfo
            // 请求
            imitationPost({
              url: '/test/saveUserInfo',
              data: {
                userInfo
              },
              success: data => {
                console.log(data)
              },
              fail: res => {
                console.log(res)
              }
            })
          },
          fail: res => {
            console.log(res)
          }
        })
      },
      fail: res => {
        console.log(res)
      }
    })
  },
  fail: res => {
    console.log(res)
  }
})

下面分析如何用Promise來進行簡化程式碼

因為微信小程式非同步api都是success和fail的形式,所有有人封裝了這樣一個方法:

promisify.js

module.exports = (api) => {
  return (options, ...params) => {
    return new Promise((resolve, reject) => {
      api(Object.assign({}, options, { success: resolve, fail: reject }), ...params);
    });
  }
}

先看最簡單的:

// 获取系统信息
wx.getSystemInfo({
  success: res => {
    // success
    console.log(res)
  },
  fail: res => {

  }
})

使用上面的promisify. js簡化後:

const promisify = require('./promisify')
const getSystemInfo = promisify(wx.getSystemInfo)

getSystemInfo().then(res=>{
  // success
  console.log(res)
}).catch(res=>{

})

getSystemInfo

可以看到簡化後的回調裡少了一個縮進,並且回呼函數從9行減少到了6行。

回呼金字塔的簡化效果

那麼再來看看最開始的那個回呼金字塔

const promisify = require('./promisify')
const login = promisify(wx.login)
const getSystemInfo = promisify(wx.getSystemInfo)

// 登录
login().then(res => {
  let code = res.code
  // 请求
  pImitationPost({
    url: '/test/loginWithCode',
    data: {
      code
    },
  }).then(data => {
    // 获取userInfo
    getUserInfo().then(res => {
      let userInfo = res.userInfo
      // 请求
      pImitationPost({
        url: '/test/saveUserInfo',
        data: {
          userInfo
        },
      }).then(data => {
        console.log(data)
      }).catch(res => {
        console.log(res)
      })
    }).catch(res => {
      console.log(res)
    })
  }).catch(res => {
    console.log(res)
  })
}).catch(res => {
  console.log(res)
})

簡化回調

可以看到簡化效果非常明顯。

同樣適用於網頁或nodejs等。

相關推薦:

微信小程式getUserInfo回呼詳解

jQuery回呼方法使用詳解

#PHP回呼函數的解析

以上是微信小程式Promise簡化回呼實例分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。