微信小程序中有些 Api 是异步的,无法直接进行同步处理。例如:wx.requestwx.showToastwx.showLoading 等。如果需要同步处理,可以使用如下方法:

提示:Async-await 方法属于ES7语法,在小程序开发工具中如果勾选es6转es5, 会报错:

ReferenceError: regeneratorRuntime is not defined

需要解决的问题都有哪些:

  1、截止到发文前小程序还不支持ES7的语法,我们到底能不能用?

  2、撸的方式又是怎样的?

实践的方式如下:

第一个问题:

  虽然小程序不支持,但是我们可以引入js库啊。双手奉上 facebook 的开源库 regenerator 下载 'packages/regenerator-runtime' 将这个文件放到自己小程序项目下的 utils 或者 lib 文件夹下。

  总共就23K不要担心包体积的问题。

  然后在使用async-awiat的页面中引入

const regeneratorRuntime = require('../../lib/regenerator-runtime/runtime')

第二个问题:

Async 跟 Await 的用法。

  Async - 定义异步函数(async function someName(){...})

  自动把函数转换为 Promise

  当调用异步函数时,函数返回值会被 resolve 处理

  异步函数内部可以使用 await

Await - 暂停异步函数的执行 (var result = await someAsyncCall();)

  当使用在 Promise 前面时,await 等待 Promise 完成,并返回 Promise 的结果

  await 只能和 Promise 一起使用,不能和 callback 一起使用

  await 只能用在 async 函数中

案例代码(一):

在根目录下新建api文件夹,里面新建index.js

// request get 请求
const getData = (url, param) => {
return new Promise((resolve, reject) => {
wx.request({
url: url,
method: 'GET',
data: param,
success (res) {
console.log(res)
resolve(res.data)
},
fail (err) {
console.log(err)
reject(err)
}
})
})
} // request post 请求
const postData = (url, param) => {
return new Promise((resolve, reject) => {
wx.request({
url: url,
method: 'POST',
data: param,
success (res) {
console.log(res)
resolve(res.data)
},
fail (err) {
console.log(err)
reject(err)
}
})
})
} // loading加载提示
const showLoading = () => {
return new Promise((resolve, reject) => {
wx.showLoading({
title: '加载中...',
mask: true,
success (res) {
console.log('显示loading')
resolve(res)
},
fail (err) {
reject(err)
}
})
})
} // 关闭loading
const hideLoading = () => {
return new Promise((resolve) => {
wx.hideLoading()
console.log('隐藏loading')
resolve()
})
} module.exports = {
getData,
postData,
showLoading,
hideLoading
}

index.js

在入口文件 app.js 中引入:

//app.js
const api = require('./api/index') App({
onLaunch: function () { },
// 全局数据中暴露api
globalData: {
api
}
})

app.js

在需要使用api 的页面中处理如下:

const app = getApp()

const api = app.globalData.api
const regeneratorRuntime = require('../../lib/regenerator-runtime/runtime')
Page({ onLoad() {
this.init()
}, // 初始化
async init() {
console.log("日志打印(1)");
await api.showLoading() // 显示loading console.log("日志打印(2)");
await this.getList() // 请求数据 console.log("日志打印(3)");
await api.hideLoading() // 等待请求数据成功后,隐藏loading console.log("日志打印(4)");
}, // 获取列表
getList() {
return new Promise((resolve, reject) => {
api.getData('http://127.0.0.1:9003/list', {
token: "043c00e6c7ff021e8cc4d394d3264cb5e8c"
}).then((res) => {
this.setData({
list: res
})
console.log("返回数据");
resolve()
})
.catch((err) => {
reject(err)
})
})
}, })

引用的页面

主要看日志的打印顺序 查看执行流程    自行改动 异步|同步 查看效果。

案例代码(二):

// pages/index/index.js

//index.js
import regeneratorRuntime from '../../utils/runtime.js'
const moment = require('../../utils/mp-moment') //获取应用实例
const app = getApp() Page({ /**
* 页面的初始数据
*/
data: { }, /**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
let that = this
// 同步执行异步函数
that.testAsync()
// 异步执行异步函数
// that.testSync()
},
async testAsync() {
let that = this
console.log(moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') + ' testAsync start')
console.log('show loading') let resultOne = await that.getValueOne();
console.log(moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') + resultOne)
let resultTwo = await that.getValueTwo();
console.log(moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') + resultTwo)
console.log('hide loading')
console.log(moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') + ' testAsync end')
},
async testSync() {
let that = this
console.log(moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') + ' testSync start')
console.log('show loading') let resultOne = that.getValueOne();
let resultTwo = that.getValueTwo(); let results = await Promise.all([resultOne, resultTwo])
console.log(moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') + results[0])
console.log(moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') + results[1]) console.log('hide loading')
console.log(moment(Date.now()).format('YYYY-MM-DD HH:mm:ss') + ' testSync end') },
getValueOne() {
let that = this
let startTime = Date.now() return new Promise (function(resolve, reject) {
setTimeout(function() {
let endTime = Date.now()
resolve(' 请求成功 one ' + moment(endTime - startTime) + 'ms')
}, 1000)
})
},
getValueTwo() {
let that = this
let startTime = Date.now() return new Promise(function (resolve, reject) {
setTimeout(function () {
let endTime = Date.now()
resolve(' 请求成功 two ' + moment(endTime - startTime) + 'ms')
}, 3000)
})
},
})

WeChat-SmallProgram:微信小程序中使用Async-await方法异步请求变为同步请求的更多相关文章

  1. 微信小程序中的不同场景,不同的判断,请求的时机

    本来5月1之前就想写一下一篇关于小程序不同场景下发送ajax请求的问题,但是放假的前一天,出了个大bug,就是因为我修改不同的场景下执行不同的逻辑造成的 1.首先,在小程序里,微信做了很多的缓存,我们 ...

  2. 全栈开发工程师微信小程序-中(中)

    全栈开发工程师微信小程序-中(中) 开放能力 open-data 用于展示微信开放的数据 type 开放数据类型 open-gid 当 type="groupName" 时生效, ...

  3. 微信小程序中同步 异步的使用

    https://www.jianshu.com/p/e92c7495da76   微信小程序中使用Promise进行异步流程处理 https://www.cnblogs.com/cckui/p/102 ...

  4. 微信小程序中使用Async-await方法异步请求变为同步请求

    微信小程序中有些 Api 是异步的,无法直接进行同步处理.例如:wx.request.wx.showToast.wx.showLoading等.如果需要同步处理,可以使用如下方法: 注意: Async ...

  5. 网页或微信小程序中使元素占满整个屏幕高度

    在项目中经常要用到一个容器元素占满屏幕高度和宽度,然后再在这个容器元素里放置其他元素. 宽度很简单就是width:100% 但是高度呢,我们知道的是height:100%必须是在父元素的高度给定了的情 ...

  6. 在微信小程序中使用富文本转化插件wxParse

    在微信小程序中我们往往需要展示一些丰富的页面内容,包括图片.文本等,基本上要求能够解析常规的HTML最好,由于微信的视图标签和HTML标签不一样,但是也有相对应的关系,因此有人把HTML转换做成了一个 ...

  7. 微信小程序中发送模版消息注意事项

    在微信小程序中发送模版消息 参考微信公众平台Api文档地址:https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html#模版消息管理 此参考地址 ...

  8. 微信小程序中placeholder的样式

    通常,现代浏览器大多支持::placeholder选择器,用于设置placeholder的样式,但是在微信小程序中并不支持这种方式,而是提供了一个专门的属性(placeholder-class)来处理 ...

  9. 微信小程序中转义字符的处理

    在微信小程序开发过程中,有时候会用到常用的一些特殊字符如:‘<’.‘>’.‘&’.‘空格’等,微信小程序同样支持对转义字符的处理,下面提供两种方法用来处理微信小程序中转义字符的处理 ...

随机推荐

  1. GoLand 设置与配置

    1. 将 tab 改为 4个空格 2. GoLand 取消 import 自动导入

  2. 位运算基础(Uva 1590,Uva 509题解)

    逻辑运算 规则 符号 与 只有1 and 1 = 1,其他均为0 & 或 只有0 or 0 = 0,其他均为1 | 非 也就是取反 ~ 异或 相异为1相同为0 ^ 同或 相同为1相异为0,c中 ...

  3. 前端的事件冒泡(例如点击一次onclick事件执行两次)解决办法

    问题概要: 当我运用antd 中 radio组件的时候发现radio组件是有bug的 就是你不能给他赋予id 和 value,同时也绑定不上onclick等事件.举个例子: 可以看到 你就算赋予了id ...

  4. iPhone UIButton图标与文字间距设置【转】

    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 150, 50)]; [button setTitle:@& ...

  5. IoT设备实践丨如果你也在树莓派上部署了k3s,你也许需要这篇文章

    前 言 树莓派是一种广泛流行的开发板,随着物联网的深入发展,树莓派大有成为IoT终端设备标准之趋势.在支持客户在IoT场景中落地k3s时,k3s在树莓派上的部署问题也就出现了.本文记录了一些其中的关键 ...

  6. 如何分析SpringBoot源码模块及结构?--SpringBoot源码(二)

    注:该源码分析对应SpringBoot版本为2.1.0.RELEASE 1 前言 本篇接 如何搭建自己的SpringBoot源码调试环境?--SpringBoot源码(一). 前面搭建好了自己本地的S ...

  7. 实验三——NFS服务器配置

    实验三——NFS服务器配置 实 验 基 本 信 息 实验名称:NFS服务器配置(3学时) 实验时间:    年 月 日 实验地点:   信工606实验室 同组同学: 实验目的: 了解NFS服务的基本原 ...

  8. DBProxy快速入门

    1. DBProxy安装 1.1 安装依赖项 CentOS yum install -y Percona-Server-devel-55.x86_64 Percona-Server-client-55 ...

  9. vlc 播放器的点播和广播服务

    vlc 是一个开源的,同时跨平台的播放器.在研究 rtsp 协议时发现,它同时还是一个强大的流媒体服务器 VLM VLM(VideoLAN Manager) 在 vlc 中是一个小型的媒体管理器,它能 ...

  10. (转)浅析epoll-为何多路复用I/O要使用epoll

    原文地址:http://www.cppfans.org/1417.html 浅析epoll-为何多路复用I/O要使用epoll 现如今,网络通讯中用epoll(linux)和IOCP(windows) ...