小程序不支持wx.request同步請求解決方法


小程序為了用戶體驗,所有的request均為異步請求,不會阻塞程序運行

百牛信息技術bainiu.ltd整理發布於博客園

所以當你需要同步請求,鎖死操作時,最好將所有的邏輯寫在success:function(){}

里面,

不然后出現返回值為空的尷尬

錯誤代碼示例:

更改后的代碼為:

  1. onShow:function(){
  2. // 頁面顯示
  3. var commonFunction = require('../../pages/index/common'),
  4. that = this;
  5. var interval = setInterval(function(){
  6. that.setData({
  7. nowTime : commonFunction.formatTime(new Date())
  8. })
  9. },1000);
  10. var request = function(latitude,longitude){
  11. wx.request({
  12. url: that.globalData.API_URL + 'getLocation',
  13. data: {
  14. latitude : latitude,
  15. longitude : longitude
  16. },
  17. method: 'GET',
  18. success: function(res){
  19. let result = res.data.data;
  20. result = JSON.parse(result);
  21. console.log(result);
  22. }
  23. });
  24. };
  25. wx.getLocation({
  26. "type" : 'gcj02',
  27. "success" : function(res){
  28. const latitude = res.latitude;
  29. const longitude = res.longitude;
  30. request(latitude,longitude);
  31. },
  32. "fail" : function(e){
  33. console.log(e);
  34. }
  35. });
  36. },
  37. 此文作用僅為填坑,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM