首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我的代码不等待回调

为什么我的代码不等待回调
EN

Stack Overflow用户
提问于 2021-07-18 16:35:47
回答 1查看 70关注 0票数 0

我正在用mineflayer编写一个“我的世界”机器人。我有一个函数,它定位一个块,并在mineflayer-pathfinder模块的帮助下转到它。

现在我的问题是,在我的机器人到达他的位置后,我想执行更多的代码,这取决于它的最终位置。所以他就等着我回调,但他不是等到他到了那个位置,而是在我设定了寻路目标之后。

下面是我的代码:

代码语言:javascript
复制
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()
        }
    })
}

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

EN

回答 1

Stack Overflow用户

发布于 2021-07-28 15:25:40

您可以使用bot.pathfinder.goto而不是bot.pathfinder.setGoal

代码语言:javascript
复制
bot.pathfinder.goto(goal, (error, result) => {
    if (!error) findMore();
})

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

代码语言:javascript
复制
bot.on("goal_reached", () => {
    findMore();
})

mineflayer pathfinder docs

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68427387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档