javascript - Async/Await 导致循环

标签 javascript typescript promise async-await

我尝试使用 Async/Await 而不是带有 Promise 的 .then() 。 使用 .then() 方法,我的代码工作正常......

当我将其更改为异步/等待时,我得到了一个循环

另一个问题:如何禁用 console.log() 中的 Promise?

谢谢……

ASCBY1
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
Promise { <pending> }
state:2
ASCBY1
state:2
ASCBY1
state:2

**这工作正常**

  
  
  private innerLoop(i,ifArray,counter,cb){
    let tempMod = new Module(null, ifArray[i].id,ifArray[i].type);
    /*FALLS CHCEK BY MODULE*/

    if(ifArray[i].timerID === 0){ //WENN ein Timer ausgeführt iwrd, dann gibt es kein Modul bzw. kein DevType, er muss aber dennoch durch alle Schleifen (ifArray) laufen. Ohne der && this.mod.... würde er bei switch case ein Fehler ausspucken weil es den DevType nicht gibt.
      if(!(this.mod === undefined)){
      //  var tempMod = new Module(ifArray[i].id,ifArray[i].type);
        setTimeout(()=>console.log(tempMod.getState()),1000);
        switch (this.mod.modulesRecievedData.DevType){
           case 0x0b:{
             if(this.mod.checkMultiSwitch(ifArray[i])){
               counter++;
             }
             break;
           }
           case 0x02:{
              console.log("ASCBY1");

              tempMod.getState().then((state)=>{
                if(state == 2) counter++;

                console.log("state:"+state);

                if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
                  this.innerLoop(i,ifArray,counter,cb);
                }else{
                  cb(counter);
                }
              });


              break;
           }
        }
        i++;
      }
    }else if(ifArray[i].timerID > 0){  /*FALLS CHECK BY TIMER*/
      var timerOnState = time[ifArray[i].timerID].timerOnState;
      if(timerOnState == true){
        counter++;
      }
      i++;
      if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
        this.innerLoop(i,ifArray,counter,cb);
      }else{
         console.log("counter3 "+counter);
        cb(counter);
      }
    }
  }

这会导致外观

private async innerLoop(i,ifArray,counter,cb){
    let tempMod = new Module(null, ifArray[i].id,ifArray[i].type);
    /*FALLS CHCEK BY MODULE*/

    if(ifArray[i].timerID === 0){ //WENN ein Timer ausgeführt iwrd, dann gibt es kein Modul bzw. kein DevType, er muss aber dennoch durch alle Schleifen (ifArray) laufen. Ohne der && this.mod.... würde er bei switch case ein Fehler ausspucken weil es den DevType nicht gibt.
      if(!(this.mod === undefined)){
      //  var tempMod = new Module(ifArray[i].id,ifArray[i].type);
        setTimeout(()=>console.log(tempMod.getState()),1000);
        switch (this.mod.modulesRecievedData.DevType){
           case 0x0b:{
             if(this.mod.checkMultiSwitch(ifArray[i])){
               counter++;
             }
             break;
           }
           case 0x02:{
              console.log("ASCBY1");
              ///////////////////////////////////
              //////HERE IS THE CHANGE///////////
              ///////////////////////////////////
              let state = await tempMod.getState();

              if(state == 2) counter++;

              console.log("state:"+state);

              if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
                this.innerLoop(i,ifArray,counter,cb);
              }else{
                cb(counter);
              }
              break;
           }
        }
        i++;
      }
    }else if(ifArray[i].timerID > 0){  /*FALLS CHECK BY TIMER*/
      var timerOnState = time[ifArray[i].timerID].timerOnState;
      if(timerOnState == true){
        counter++;
      }
      i++;
      if(i < ifArray.length){//NUR WENN TIMERID == 0 ist, sonst zählt er den Timer mit obwohl da keine ID + type dahinter steckt.
        this.innerLoop(i,ifArray,counter,cb);
      }else{
         console.log("counter3 "+counter);
        cb(counter);
      }
    }
  }

模块类

	getState(){
		let promise = new Promise((resolve)=>{
			this.db.getStateOfModule(this._id,this._type,
				(data)=>{this._state = data[0].state; resolve(data[0].state);}
			);
		});

		return promise;
	}

最佳答案

Module.getState 返回一个 promise 。

线路setTimeout(()=>console.log(tempMod.getState()),1000); 等待 1000 毫秒,然后控制台记录 tempMod.getState() 的结果,这是一个未兑现的 promise 。

如果您不想获得 Promise { <pending> }在控制台中。您可以将其更改为

setTimeout(() => tempMod.getState().then((result) => {
  console.log(result)
}), 1000);
<小时/>

关于循环问题。当您使用.then()时。 .then() 之后的其余代码将立即运行。特别是i++ 。仅 then 内的代码回调将会延迟。

当您将其更改为 await 时。整个函数将停止执行,直到 promise 解决为止。这意味着i++不会被执行。

我假设ifArray.length是 1,i 从 0 开始。所以当你到达 if(i < ifArray.length){ 时当使用await(因为i++没有执行)时,这将是正确的,这将导致innerLoop被再次调用。 同样的事情将会不断发生,如 i++永远不会被执行。

关于javascript - Async/Await 导致循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60238606/

相关文章:

javascript - 回发期间的进度条 asp.net

事件的 typescript 字符串文字方法重载

javascript - 如何让 angular2 在 eclipse 中使用 typescript 工作

css - 如何覆盖样式组件中的 css 类

javascript - 在 Promise 中 resolved 或 rejected 之后你应该返回一些东西吗?

javascript - 上传前显示缩略图

javascript - Bootstrap 验证和 Bootstrap 选择

javascript - 在循环返回之前等待 http 成功 - Angular 4

javascript - 声明一个等待 promise 的函数

javascript - q.all用嵌套异步 forEach 解决