I'm confused by Synchronous/Asynchronous processing of JavaScript.
What I want to do is below. When self_driving() is called, then get_direction_by_sensor() is called and using the direction, moter starts running by move_to_direction(direction). This process repeats 5 times.
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)
};
So I want this code to run like this.
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()
But actually it runs like this.
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()
How can I fix this code? Thanks.
======== MORE DETAILED INFO ========
move_to_direction() calles Macro of webiopi written by Python.
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');
}
});
}
move_to_directionfunction. What I want to do is finish all the (sub) functions inmove_to_directionand go to nextmove_to_direction.