【问题标题】:Why doesn't my code wait for the callback为什么我的代码不等待回调
【发布时间】:2021-07-18 08:35:47
【问题描述】:

我正在用 mineflayer 编写一个 Minecraft 机器人。我有一个函数可以定位一个块并在 mineflayer-pathfinder 模块的帮助下找到它。

现在我的问题是,在我的机器人到达他的位置后,我想执行更多代码,具体取决于他的最终位置。为了让他等到那里,我已经尝试过回调,但他不会等到他就位,而是在我设定寻路目标之后。

这是我的代码:

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()
        }
    })
}

如果你有任何其他想法,我如何等待寻路完成我很乐意尝试

【问题讨论】:

    标签: javascript callback wait mineflayer


    【解决方案1】:

    您可以使用bot.pathfinder.goto 代替bot.pathfinder.setGoal

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

    当达到目标时还有一个事件

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

    mineflayer pathfinder docs

    【讨论】:

      猜你喜欢
      • 2022-01-21
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多