for循环中的异步处理(异步变同步)

转载:https://www.cnblogs.com/xiujun/p/10637037.html

前沿:参考ES6语法的async/await的处理机制

先上一段代码

function getMoney(){
    var money=[100,200,300]  
    for( let i=0; i<money.length; i++){
        compute.exec().then(()=>{
            console.log(money[i])
            //alert(i)
        })
    }
}
//compute.exec()这是个异步方法,在里面处理一些实际业务
//这时候打印出来的很可能就是300,300,300(因为异步for循环还没有等异步操作返回Promise对象过来i值已经改变)
async function getMoney(){
    var money=[100,200,300]  
    for( let i=0; i<money.length; i++){
        await compute.exec().then(()=>{
            console.log(money[i])
            //alert(i)
        })
    }
}
//关键字async/await  async告诉getMoney方法里面存在异步的操作,await放在具体异步操作(方法)前面,意思是等待该异步返回Promise才会继续后面的操作
function getMoney(i) {

  var money=[100,200,300]
  compute.exec().then(() => {
    if ( i < money.length ) {  
      console.log(money[i]);
      i++;
        getMoney(i);
      }
   });
}
getMoney(0);//开始调用
//用递归来实现自我循环(具体循环在then里面,可以确保前面的compute.exec()的异步操作完成).then()是返回了Promise对象为resolve后才进行的(可以了解一下Promise对象)
原文地址:https://www.cnblogs.com/xiong88/p/12718565.html