Home >WeChat Applet >Mini Program Development >What are the two ways to synchronize WeChat applet execution in sequence?

What are the two ways to synchronize WeChat applet execution in sequence?

王林
王林forward
2021-03-17 11:41:536232browse

What are the two ways to synchronize WeChat applet execution in sequence?

Foreword:

There are two ways to synchronize the execution of small programs in sequence:

The first way: callback function execution, the latter method Write to the previous callback function to achieve sequential execution

Disadvantages: too much nesting, code confusion

Second method: async-await synchronous execution, this method waits for the previous method Continue execution only after execution is completed

Advantages: High code readability

Take checking text security as an example and give two different methods of code for reference

async- await

/**
 * 同步检查是否包含敏感词
 */
 
// async function checkString(content) {
//   try {
//     var res = await wx.cloud.callFunction({
//       name: 'checkString',
//       data: {
//         content: content,
//       }
//     });
//     if (res.result.errCode == 0)
//       return true;
//     return false;
//   } catch (err) {
//     console.log(err);
//     return false;
//   }
// }
 
 
	// pubcom: async function (e) {
	// 	wx.showLoading({
	// 		title: '加载中',
	// 		mask: true
	// 	})
 
	// 	var that = this
	// 	var doc_id = that.data.commentID
	// 	var content = that.data.comcon
	// 	var formId = e.detail.formId;
	// 	if (!content) {
	// 		return
	// 	}
	// 	var isCheck = await common.checkString(content);
	// 	if (!isCheck) {
	// 		wx.showToast({
	// 			title: '含有敏感词',
	// 			image: "/assets/icon/icon-warning.png",
	// 		});
	// 		return
	// 	}
    //后续代码
 
 	

(Learning video sharing: php video tutorial)

Callback method

/**
 * 异步检查
 */
function checkString(content,success,fail){
  wx.cloud.callFunction({
    name: 'checkString',
    data: {
      content: content,
    }
  }).then(res => {
    console.log(res);
    if (res.result.errCode == 0)
			success(res);
  }).catch(err => {
    console.error(err);
		fail(err);
  });
}
 
pubcom: function (e) {
		wx.showLoading({
			title: '加载中',
			mask: true
		})
 
		var that = this
	
		var content = that.data.comcon
		
		if (!content) {
			return
		}
		common.checkString(content, function (res) { 
			//成功代码
		}, function (err) {
            //失败
			wx.showToast({
				title: '含有敏感词',
				image: "/assets/icon/icon-warning.png",
			});
			return});
	},

Related recommendations: 小program development tutorial

The above is the detailed content of What are the two ways to synchronize WeChat applet execution in sequence?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete