学无先后,达者为师

网站首页 编程语言 正文

小程序 onLaunch 与 onLoad 异步问题的解决方案

作者:ZionHH 更新时间: 2022-05-12 编程语言

在小程序中,我们一般在onLaunch中发起登录请求,由于是请求是异步的,在onLoad之后才执行完登录请求,如果在onLoad中需要使用请求后的数据,会发现取不到值,以下是一些解决方式,可以按自己所需使用。

  1. 使用回调函数
// app.js
onLaunch () {
	wx.login({
		success: result => {
			wx.request({
				url: 'test.php' // 示例
				data: {...},
				success: res => {
					this.globalData.openId = res.data.openId
					 // 回调
					if (this.loginCallback) this.loginCallback(res.data)
				},
				fail: err => {
					// 需要的话请求失败处也可以使用回调
				}
			})
		}
	})
}
// page.js
onLoad () {
	const app = getApp()
	if (app.globalData.openId) {
		// do something
	} else {
		app.loginCallback = (data) => {
			// do something
		}
	}
}
  1. 使用Promise
// app.js
App({
	initLogin () {
		return new Promise((resolve, reject) => {
			wx.login({
				success: result => {
					wx.request({
						url: 'test.php' // 示例
						data: {...},
						success: res => {
							resolve(res.data)
						},
						fail: err => {
							reject('error')
						}
					})
				}
			})
		})
	}
})
// page.js
onLoad () {
	const app = getApp()
	app.initLogin().then(res => {
		// do something
	}).catch(err => {})
}
  1. 使用Object.defineProperty监听
// app.js
watch (method) {
	let obj = this.globalData
	// 这里监听 openId
	Object.defineProperty(obj, "openId", {
		configurable: true,
		enumerable: true,
		set: function (value) {
			method(value);
		},
		get: function () {
			return this.globalData
		}
	})
}
onLaunch () {
	wx.login({
		success: result => {
			wx.request({
				url: 'test.php' // 示例
				data: {...},
				success: res => {
					this.globalData.openId = res.data.openId
				}
			})
		}
	})
}
// page.js
onLoad () {
	const app = getApp()
	app.watch(this.watchBack)
}
watchBack (openId) {
	if (openId) {
		// do something
	}
}
  1. 使用getCurrentPages
// app.js
onLaunch () {
	wx.login({
		success: result => {
			wx.request({
				url: 'test.php' // 示例
				data: {...},
				success: res => {
					const currentPage = wx.getCurrentPages()[0]
					// 触发当前页的init方法
					currentPage.init(res.data)
				}
			})
		}
	})
}
// page.js
init (data) {
	// do somethine
}
  1. reLaunch重载页面
// app.js
onLaunch () {
	wx.login({
		success: result => {
			wx.request({
				url: 'test.php' // 示例
				data: {...},
				success: res => {
					// 请求结果存到了storage里,再跳到页面可以获取到storage里的数据
					wx.reLaunch({
						url: '/pages/n-index/n-index',
					})
				}
			})
		}
	})
}
  1. 设置启动页

你有什么更完美的解决方法,快在下方评论一起讨论吧。

原文链接:https://blog.csdn.net/z291493823/article/details/121215584

栏目分类
最近更新