Synchronization is the execution of the next task after a task is executed. Asynchronous means that multiple tasks are executed at the same time. Therefore, if there is task B that requires the result of task A, it involves the problem of asynchronous flow control.
Callback Function
This is the most basic method of asynchronous programming
function f1(callback) { console.log('start to run f1.'); setTimeout(function () { console.log('f1 is finished. callback f2'); callback(); },3000); } function f2() { console.log('start to run f2.'); } f1(f2);
The running result is
start to run f1.
f1 is finished. callback f2
start to run f2.
Promise
Promise object is a new specification of ES6, each asynchronous task returns a Promise object, which has a then method, allowing to specify callback function
var getTestJson = function (url) { var promise = new Promise(function(resolve,reject){ var xhr = new XMLHttpRequest(); xhr.open("GET",url,true); xhr.onreadystatechange = function () { console.log("this.readyState:"+this.readyState+",this.status:"+this.status); if(this.readyState !== 4) { return; } if(this.status === 200){ resolve(this.response); } else { reject(new Error(this.statusText)); } } xhr.responseType = "json"; xhr.setRequestHeader("Accept","application/json"); xhr.send(); }); return promise; }; var url = "http://localhost:8000/getJson"; getTestJson(url).then(function (json) { console.log('get the data back',json); },function (error) { console.log('error',error); });
getTestJson is an asynchronous task. After the task is executed, the .then method will be called
http://localhost:8000/getJson This address is the background that I use locally with nodejs