Promise对象和回调函数,解决异步数据传递问题

it2022-05-05  149

下面的代码例子,均已小程序的异步请求数据为案例来说明

1.利用回调函数,来解决异步数据传递问题

1 异步操作api.js 2 const getBooks = (url, callback) => { 3   wx.request({ 4   url: url, 5   method: 'GET', 6   header: { 7   "Content-Type": "json" 8   }, 9   success: function (res) { 10   console.log(res) 11   callback(res) 12   } 13   }) 14 } 15 module.exports = { 16 getBooks: getBooks 17 } 18 19 引入api.js 20 21 api.getBooks('参数',回调函数) 22 23 写法一: 24 api.getBooks('https://api.douban.com/v2/movie/search?tag=喜剧&count=4', res => { 25 console.log(res) 26 }) 27 28 写法二: 29 30 let x = () => {console.log(res)} 31 api.getBooks('参数', x)

2.利用Promise来解决异步回调数据传递的问题

异步操作api.js const getBooks = (url) => {   return new Promise((resolve,reject) => {     wx.request({       url: url,       method: 'GET',       header: {     "Content-Type": "json"       },       success: function (res) {      resolve(res)       }     })   }) } module.exports = { getBooks: getBooks } 引入api.js api.getBooks('https://api.douban.com/v2/movie/search?tag=喜剧&count=4').then(res => { console.log(res) })

以上两种方法均可以解决异步操作中数据传递的问题,也是比较简单,比较实用的两种方法

转载于:https://www.cnblogs.com/songdongdong/p/7530852.html


最新回复(0)