Promise-javascript | MDN
Promise-Liaoche's official website
It is very convenient to use promise to make asynchronous operations synchronous, and I have been learning for a long time about the use of this promise when I am having a synchronous execution of an indeterminate number of asynchronous operations (at the time because of the lack of understanding and a long struggle), and to summarize, hoping to help everyone
Single Asynchronous Operation synchronization
<div id="box"></div><script> var box = document.querySelector(‘#box‘) var p = new Promise(function(resolve, reject){ setTimeout(function(){ box.innerHTML += ‘网络请求<br>‘; resolve() }, 1000) }) p.then(function(resolve){ box.innerHTML += ‘结束<br>
Determining the number of asynchronous Operation Synchronizations<div id="box"></div><script> var p = new Promise(function(resolve, reject){ setTimeout(function(){ box.innerHTML += ‘建立连接<br>‘; resolve(‘ok‘) }, 1000) }) function post_sth(data){ return new Promise(function(resolve, reject){ setTimeout(function(){ box.innerHTML += ‘post网络请求,此时data=‘+data+‘ <br>‘; resolve(data+‘|post‘) }, 1000) }) } function get_sth(data){ return new Promise(function(resolve, reject){ setTimeout(function(){ box.innerHTML += ‘get网络请求,此时data=‘+data+‘ <br>‘; resolve(data+‘|get‘) }, 1000) }) } p.then(post_sth).then(get_sth).then(post_sth).then(function(data){ box.innerHTML += ‘最后data=‘+data+‘<br>
Indefinite number of asynchronous operation synchronization<div id="box"></div><script> var p = new Promise(function(resolve, reject){resolve()}) /** function 返回function(供本then用) 返回Promise(供下一个then用) */ function get_request_sth_func(i){ return function request_sth(){ return new Promise(function(resolve, reject){ setTimeout(function(){ box.innerHTML += ‘请求‘+i+‘<br>‘; resolve() }, Math.round(Math.random()*1000)) }) } } for (var i = 0; i < 20; ++i) { p = p.then(get_request_sth_func(i)) } p.then(function(){ box.innerHTML += ‘完成<br>
Js-promise (causes asynchronous operations to execute synchronously)