我正在使用Node.js
模块AR-Drone 来控制我的鹦鹉ar.无人机2.0。
client.takeoff();
client.after(5000, function () {
this.on("navdata", function (d) {
if (d.demo) {
//totaly and totalx are calculated here using navdata
if (totaly > 85) {
// if the deviation is far to the right more than 85 mm
console.log("moving left ");
client.left(0.15);
sleep(500).then(() => {
client.stop();
});
} else if (totaly < -85) {
// if the deviation is far to the left more than 85 mm
console.log(" moving right");
client.right(0.15);
sleep(500).then(() => {
client.stop();
});
} else if (totalx < 3000) {
client.front(0.02);
sleep(250).then(() => {
client.stop();
});
console.log("moving forward");
} else {
client.land();
}
}
});
});
我的问题是,当我编写sleep(500)
然后做某事时,程序实际上是等待 500 毫秒还是"if 周期"同时运行? 发送到无人机的操作的顺序是什么?
sleep
函数不会在持续时间内阻塞线程,而是计划回调在时间过后立即运行。但是,回调外部的代码同步运行。
client.front(0.02); // this runs first
sleep(250).then(() => {
// this runs third (after 250ms)
client.stop();
});
console.log("moving forward"); // this runs second
因此,如果您想保证某些东西"在睡眠后"运行,则必须将其放入.then()
回调中或使用async/await
.
async/await
示例:
async function run() {
await sleep(500);
// everything below is guaranteed to run after the "sleep"
console.log('500 ms have passed')
}
run();