【发布时间】:2020-04-25 20:30:40
【问题描述】:
我正在尝试将值推送到数组中,但是这些值以错误的顺序推送。
//Returns ongoing stream of the decibels in the room
async getNoise() {
let subscription = this.dbMeter.start().subscribe(data => {
this.noiseDb = data;
return data;
});
} //Returns your current location
getPosition() {
return new Promise((res, rej) => {
navigator.geolocation.getCurrentPosition(res, rej);
});
}
async startTimer() {
this.interval = setInterval(async() => {
interface pos {
coords ? : any,
}
var position: pos = await this.getPosition(); // wait for getPosition to complete
this.getNoise();
objects.push({
lat: position.coords.latitude,
long: position.coords.longitude,
noise: this.noiseDb
});
}, 500);
}
当有 2 秒延迟时,这可以正常工作,但是当有 1 秒延迟或半秒延迟时,如上所示,值会以错误的顺序推送到数组中,并且相同的值用于多个条目.例如,
[{"lat":55.7558,"long":4.4784,"noise":45.58059,"time":"1.01"},
{"lat":55.7558,"long":4.4784,"noise":45.58059,"time":"2.01"},
{"lat":55.7558,"long":4.4784,"noise":40.197384,"time":"4.01"},
{"lat":55.7558,"long":4.4784,"noise":40.197384,"time":"3.01"}]
我相信我需要使用 Promise.all() 但我不确定如何实现它。谁能帮帮我?
【问题讨论】:
-
this.noiseDb是什么?为什么打电话给this.getNoise()时不等待? -
noiseDb 只是我在开始时初始化的一个变量,每当我等待 this.getNoise() 时,推送到数组的值始终是未定义的
-
你认为 getCurrentPosition 什么时候会给你一个不同的值?
-
我们假设用户正在移动,例如跑步或骑自行车。所以每 500 毫秒 getCurrentPosition 应该返回一个不同的值。
标签: javascript arrays promise es6-promise