處理函數之間的異步問題,使其同步進行的其中一種方法,就是使用Promise。Promise在ES6中被提出。
使用示例如下:
假如有三個函數,要求按getone、gettwo、getthree的順序執行。函數參數為Promise特有的resolve和reject,reslove和reject可在函數中返回結果。
1 //異步方法一 2 function getone(resolve,reject){ 3 setTimeout(function(){ 4 resolve("1"); 5 },3000) 6 } 7 //異步方法二 8 function gettwo(resolve,reject){ 9 setTimeout(function(){ 10 resolve("2"); 11 },3000) 12 } 13 //異步方法三 14 function getthree(resolve,reject){ 15 setTimeout(function(){ 16 resolve("3"); 17 },3000) 18 }
將getone函數作為參數生成Promise對象,用then來串聯,result能拿到上一個函數返回的結果,then里面返回的是一個新的Promise對象,從而實現串聯。
1 var result = new Promise(getone) 2 .then(function(resultone){ 3 console.log('----------one------------'); 4 console.log(resultone); 5 return new Promise(gettwo); 6 }) 7 .then(function(resulttwo){ 8 console.log('----------two------------'); 9 console.log(resulttwo); 10 return new Promise(getthree); 11 }) 12 .then(function(resultthree){ 13 console.log('-----------three---------'); 14 console.log(resultthree); 15 }) 16 .catch(function(err){ 17 console.log(err); 18 })
結果如下:
從而實現了這三個函數間的同步執行和前后傳參。