Home > Web Front-end > JS Tutorial > body text

Introduction to Javascript asynchronous programming methods

零下一度
Release: 2017-07-20 17:11:16
Original
1311 people have browsed it

In the process of JavaScript development, we will inevitably encounter some asynchronous programming scenarios, whether it is the front-end ajax request or the various asynchronous APIs of node. The following is a summary of JavaScript asynchronous programming during the work and study process. A summary of the usage of common methods

Several methods of asynchronous programming in javascript

The asynchronous mode programming that is currently used more frequently in work has the following methods

One callback function

This is the most basic method of asynchronous programming. Suppose there are two functions f1 and f2, the latter waits for the execution result of the former

f1();f2();
如果f1是一个很耗时的任务,可以考虑改写f1,把f2写成f1的回调函数
function f1(callback){   setTimeout(function(){       
// f1的任务代码             
//执行回调函数      callback()    },1000)}执行代码就变成下面这样:
Copy after login

f1(f2);//Call

In this way, we turn synchronous operations into asynchronous operations. F1 will not block the running of the program. It is equivalent to executing the main logic of the program first and delaying the execution of time-consuming operations.

Specific Example:

Since the ajax request is asynchronous, sometimes we need to get the data after the ajax request before performing other operations. At this time, the callback function will help us solve this problem. The specific code is as follows:

import $ from 'jquery'function getData(callback){  var url="http://xxx.com/activity/v1/homepage/index";  var data={      "cityId":110100,      "type":"coupon"
  }
  $.ajax({
       url:url,
       type:'get',
       dataType:'jsonp',
       jsonp:'callback',
       data:data,
       success:function(resp){        if(resp.status==200 && resp.data){            var item = resp.data[0] && resp.data[0].coupon;            if(callback){
                callback(item) //执行回调函数            }
        }
       },
       error:function(err){
            console.log("error")
       }
  })
}function getItem(data){    if(data){        //得到数据进行处理
        var url = data.moreUrl;
        alert(url)
    }
}
 getData(getItem) //调用二 发布/订阅 模式
Copy after login

We assume that there is a "signal center". When a certain task is executed, it "publish" a signal to the signal center. Other tasks can "subscribe" to the signal center to know When can I start executing it myself. This is called the "publish-subscribe pattern" (publish-subscribe pattern), also known as the "observer pattern" (observer pattern).

There are many implementations of this pattern. The following is Ben Alman’s Tiny Pub/Sub, which is a plug-in for jQuery.

function PubSub(){  this.handlers = {};
}
PubSub.prototype = {
  on:function(eventType,handler){    var self = this;    if(!(eventType in self.handlers)){
        self.handlers[eventType] = [];
    }
     self.handlers[eventType].push(handler);      return this;
  },
  trigger:function(eventType){    var self = this;    var handlerArgs = Array.prototype.slice.call(arguments,1);    for(var i=0;i<self.handlers[eventType].length;i++){
      self.handlers[eventType][i].apply(self,handlerArgs)
    }    return self;
  }
}
Copy after login

Specific call:

var pubsub=new PubSub();function getData(){  var url="xxx.com/activity/v1/homepage/index";  
var data={      "cityId":110100,      "type":"coupon"
  }
  $.ajax({
       url:url,
       type:&#39;get&#39;,
       dataType:&#39;jsonp&#39;,
       jsonp:&#39;callback&#39;,
       data:data,
       success:function(resp){        if(resp.status==200 && resp.data){            
       var item = resp.data[0] && resp.data[0].coupon;
            pubsub.trigger(&#39;done&#39;,item) //发布事件        }
       },
       error:function(err){
            console.log("error")
       }
  })
}//订阅事件pubsub.on(&#39;done&#39;,function(data){
  getItem(data)
})function getItem(data){
  alert(&#39;start&#39;)
  console.log(&#39;data=&#39;+data)    if(data){        //得到数据进行处理
        var url = data.moreUrl;
        alert(url)
    }
}
 getData() //调用
Copy after login

Three Promise objects

The Promise object is a specification proposed by the CommonJS working group to provide a unified interface for asynchronous programming

Used in combination with async and await provided by es7, the code is as follows:

import $ from &#39;jquery&#39;function getData()
{  return new Promise((resolve,reject) => {     
var url="http://xxx.com/activity/v1/homepage/index";     
var data={        "cityId":110100,        "type":"coupon"      }      
$.ajax({         url:url,         type:&#39;get&#39;,         dataType:&#39;jsonp&#39;,         
jsonp:&#39;callback&#39;,         data:data,         success:function(resp){            
if(resp.status==200 && resp.data){              var item = resp.data[0] && resp.data[0].coupon;               
resolve(item)            }         },         
error:function(err){           reject("error")         }      })  })}
function getItem(data){    if(data){        //得到数据进行处理        
var url = data.moreUrl;        alert(url)    }}
const testAsync = async () => {  var data = await getData();  getItem(data); }
//调用testAsync();
Copy after login


The above is the detailed content of Introduction to Javascript asynchronous programming methods. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!