首页 > 解决方案 > 为什么 setTimeout 不返回我期望的值?

问题描述

我希望函数“getRandomSave”返回一个异步值,这就是我使用 setTimeout 的原因,它在控制台中工作得很好,但我不能让它返回控制台中显示的值。

在服务中:

  getRandom(length){

    let jsonlength = length
    let a = 0;
    let randomNumber = new Array()


    var myInterval = setInterval(function(){
      
      a++

      if (a > jsonlength) {

        this.randomNumber = randomNumber;
        clearInterval(myInterval);

      }else{
         randomNumber.push(Math.ceil(Math.random()*10))
      }

    },.1)

    return new Promise((resolve)=>{
        setTimeout(()=>{resolve(randomNumber)}, 1000)
     })
     .then(x =>{return x})

  }
  
    getRandomSave(){
        setTimeout(function(){
            return this.randomNumber
        },200)
    }

执行时(在组件中):

  randomNumber(){ 

    let accesoriosJsonLength:number = this.accesoriosJson.length

    if (this.browserRefresh) {

        this.accesoriosService.getRandom(accesoriosJsonLength)
        .then(valor => console.log(valor))

    }else{
      this.accesoriosService.getRandomSave()
      console.log(this.accesoriosService.getRandomSave()); //undefined
    }

}

标签: javascriptangularasynchronoussettimeout

解决方案


推荐阅读