我对JavaScript的同步/异步处理感到困惑。
我想做的如下。当调用self_driving()
时,然后调用get_direction_by_sensor()
并使用该方向,电机将由move_to_direction(direction)
开始运行。此过程重复5次。
function get_direction_by_sensor(){
// code for getting direction from sensor
return direction
};
function move_to_direction(direction){
direction = get_direction_by_sensor()
// code for driving motor to the direction
};
function self_driving_loop(maxCount, i) {
if (i <= maxCount) {
move_to_direction();
setTimeout(function(){
self_driving_loop(maxCount, ++i)
}, 1000);
}
};
function self_driving() {
self_driving_loop(5, 1)
};
所以我希望这段代码像这样运行。
1. get_direction_by_sensor()
1. move_to_direction()
2. get_direction_by_sensor()
2. move_to_direction()
3. get_direction_by_sensor()
3. move_to_direction()
4. get_direction_by_sensor()
4. move_to_direction()
5. get_direction_by_sensor()
5. move_to_direction()
但是实际上它是这样运行的。
1. get_direction_by_sensor()
2. get_direction_by_sensor()
3. get_direction_by_sensor()
4. get_direction_by_sensor()
5. get_direction_by_sensor() // this direction is used for moving
5. move_to_direction()
如何解决此代码? 谢谢。
=========详细信息=======
move_to_direction()
调用由Python编写的webiopi宏。
function move_to_direction() {
w().callMacro('get_direction_to_move', [TRIG_F ,ECHO_F ,TRIG_R ,ECHO_R ,TRIG_L ,ECHO_L ,TRIG_B ,ECHO_B], function(macro, args, resp) {
console.log(resp) // DEBUG
if(resp == "forward") {
change_direction('FOWARD');
} else if(resp == "right") {
change_direction('RIGHT');
} else if(resp == "left") {
change_direction('LEFT');
} else if(resp == "backward") {
change_direction('BACKWARD');
}
});
}
答案 0 :(得分:2)
settimeout必须包装有一个Promise,以便可以等待它。参见
function self_driving_loop(maxCount, i) {
return new Promise(resolve => {
if (i <= maxCount) {
move_to_direction();
setTimeout(function(){
self_driving_loop(maxCount, ++i)
resolve()
}, 1000);
}
})
};
在 async 函数中以这种方式调用
await self_driving_loop(maxCount, i)