Why doesn't my code wait for the callback

581 Views Asked by At

I'm programming a minecraft bot with mineflayer. I have a function that locates a block and goes to it with the help of the mineflayer-pathfinder module.

Now my problem, after my bot is at his location I want to execute more code, depending on his final location. So that he waits to be there I've tried it with a callback, but he doesn't wait until he's at the position, but right after I set the pathfinding goal.

Here's my Code:

function getBlock(){
    const findBlock = bot.findBlock({
        matching: mcData.blocksByName["oak_log"].id,
        maxDistance: 128,
        count: 1
    })

    console.log(findBlock)

    if(!findBlock){
        bot.chat("I can't find any oak_log")
        return;
    }else{
        p = findBlock.position
        bot.chat("I found some oak_log at " + p)

        distance(p, bot.entity.position)
        setPath(p)
    }
}

function setPath(p){
    const goal = new GoalBlock(p.x, p.y, p.z)
    bot.pathfinder.setGoal(goal, (error) => {
        //Further code to execute
        bot.chat("Arrived")
        if(error){
            console.log(error)
        }else{
            bot.chat("Got one Oak Log")
            findMore()
        }
    })
}

If you have any other ideas, how I can wait for the pathfinding to finish I'll be happy to try that

2

There are 2 best solutions below

0
On

Pathfinder has promises now :

function setPath(p) {
  bot.pathfinder.goto(
    new GoalBlock(p.x, p.y, p.z)
  ).then(result => {
    bot.chat('Arrived');
    console.log(result);
    findMore();
  }).catch(err => {
    console.log(err);
  });
}
0
On

you can use bot.pathfinder.goto instead of bot.pathfinder.setGoal

bot.pathfinder.goto(goal, (error, result) => {
    if (!error) findMore();
})

there's also an event for when the goal is reached

bot.on("goal_reached", () => {
    findMore();
})

mineflayer pathfinder docs