Usage of ES6 Promise, ES7async/await asynchronous processing synchronization, asynchronous processing evolution history

what is promise

        Promise is a solution to asynchrony, essentially a constructor that can be used to instantiate an object.

        There are resolve, reject, and all on the object, and then and catch methods on the prototype. The promise object has three states: pending (initial state/in progress), resolved or fulfilled (successful), rejected (failed)

1.0 version callback

Call part:

onLoad(){
    	this.getNav(res=>{
				let id = res;
				// console.log(id);
				this.getNews(id,res2=>{
					// console.log(res2);
					let id = res2;
					this.getComment(id,res=>{
						console.log(res);
					})
				})
			})
},

 Encapsulated function part:

methods: {
    //先获取导航分类接口,将结果进行返回,到调用函数的地方获取
    getNav(callback){
      uni.request({
        url:"https://ku.qingnian8.com/dataApi/news/navlist.php",
        success:res=>{
          callback(res)
        }
      })
    },

    //获取文章数据,将文章列表进行返回
    getArticle(id,callback){
      uni.request({
        url:"https://ku.qingnian8.com/dataApi/news/newslist.php",
        data:{
          cid:id
        },
        success:res=>{
          callback(res)
        }
      })
    },

      //获取文章下的所有评论
      getComment(id,callback){
        uni.request({
          url:"https://ku.qingnian8.com/dataApi/news/comment.php",
          data:{
            aid:id
          },
          success:res=>{
            callback(res)
          }
        })
      }
}

Version 2.0Promises

Call part:

onLoad(){
  this.getNav().then(res => {
				// console.log(res);
				let id = res.data[0].id;
				return this.getNews(id);
			}).then(res=>{
				let id = res.data[1].id
				return this.getComment(id)
			}).then(res=>{
				console.log(res);
			}).catch(err=>{
				console.log(err);
			})
}

Package function part:

	methods: {
			// 获取导航列表
			getNav() {
				return new Promise((reolve, reject) => {
					uni.request({
						url: "https://ku.qingnian8.com/dataApi/news/navlist.php",
						success: res => {
							reolve(res)
						},
						fail: err => {
							reject(err)
						}
					})
				})
			},
			// 获取新闻列表
			getNews(id) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: "https://ku.qingnian8.com/dataApi/news/newslist.php",
						data: {
							cid: id
						},
						success: res => {
							resolve(res)
						},
						fail:err=>{
							reject(err)
						}
					})
				})

			},
			// 获取当前新闻评论列表
			getComment(id) {
				return new Promise((resolve,reject)=>{
					uni.request({
						url: "https://ku.qingnian8.com/dataApi/news/comment.php",
						data: {
							aid: id
						},
						success: res => {
							resolve(res)
						},
						fail:error=>{
							reject(err)
						}
					})
				})
				
			}
		}

Promise.all encapsulates a unified processing scheme for multiple objects

calling part

onLoad(){
// 可用作loading加载的制作方法
    	uni.showLoading({
				title:"数据加载中....."
			})
			let p1 = this.getNav();
			let p2 = this.getNews(51);
			let p3 = this.getComment(251);
			Promise.all([p1,p2,p3]).then(res=>{
				console.log(res);
				uni.hideLoading()
			})
}

 ※async/await asynchronous processing and synchronous refactoring of code

These two commands come in pairs:

If you use await without using the async command in the function, an error will be reported.

If you use async directly without await, no error will be reported, but the returned function is very promise.

Example code:

// 调用代码
async onLoad() {
        let res,id;
			res = await this.getNav()
			id = res.data[0].id;
			
			res = await this.getNews(id);
			id = res.data[1].id;
			
			res = await this.getComment(id);
			console.log(res);
			
			
		},
// 封装代码和上面的promise代码相同

 You can see that onload is a function. This function must have an async command. In the part of calling the function, an await is added in front of it. The meaning of this command is to assign the returned value to the res variable after the asynchronous method of this line is executed successfully. , and then you can go to the next line of code, which is to change the original asynchronous programming to synchronous programming

same/asynchronous

 

Summary : If there is no dependency on the network request, the asynchronous request is the most efficient, but the next method depends on the result of the previous network request, so the await command must be used for a long time to wait for the asynchronous result to return before executing the following code.

note link

Guess you like

Origin blog.csdn.net/weixin_39891473/article/details/129852896