簡體   English   中英

為什么我的代碼不等待回調

[英]Why doesn't my code wait for the callback

我正在用 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()
        }
    })
}

如果您有任何其他想法,我如何等待尋路完成我很樂意嘗試

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

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

當達到目標時還有一個事件

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

mineflayer 探路者文檔

探路者現在有承諾

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM