javascript - 为什么 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
}
}
解决方案
推荐阅读
- winforms - Winforms TextBox 垂直对齐与 FixedSingle 边框
- javascript - 如何使用“onclick”分隔我的输出并将数据格式化为每页 20 个?
- php - 在 PHP 中使用关联数组的 mysql UPDATE 语句
- powershell - 从 TFS 为 powershell 任务预配 Azure RM 环境
- http - 同时使用“Expires: 0”、“no-cache”、“no-store”、“max-age=0, must-revalidate”——有什么用?
- python - 合并重叠的边界框,替换为周围的边界框
- java - ModelMapper 字段映射
- java - Java - Nested classes in other files
- c# - Moq 验证来自不同方法的调用计数
- asp.net - (vb) DataBinding 时出现错误“无法找到请求的 .Net Framework 数据提供程序”