【问题标题】:Using async function to stockfish postMessage使用异步函数来收集 postMessage
【发布时间】:2021-01-29 20:13:20
【问题描述】:

我尝试与stockfish.js 合作,但我遇到了这个问题。我还使用@ninjapixel/chess 比原来的methods 更容易。

(async function() {
    console.log('test1`');
    console.log(chess.ascii());
    await stockfish.postMessage('go depth 15');
    console.log(chess.ascii()); // this should change, but it doesn't
    console.log('test2');
})();

为什么 async functionawait keyword 不起作用? 为什么test2test3之前先被记录,因为我使用的是异步函数,它应该工作,但它没有,这是为什么?

这是我处理onmessage的方式:

stockfish.onmessage = (e) => {
    let info = e.data ? e.data : e;
    if (info.includes('bestmove') || info.includes('ponder')) {
        const bestmove = info.split(/ +/)[1];
        const ponder = info.split(/ +/)[3];
        chess.move(bestmove, {
            promotion: 'q',
            sloppy: true
        });
        // test2 was logged first before this
        console.log('test3'); // ascii worked in this part
        stockfish.postMessage(`position fen ${chess.fen()}`); // update fen of stockfish
    }
};

如果没有办法解决这个问题,那么我真的应该依赖onmessage 回复吗?因为我想做的是在我做 postMessage 之后我想在 postMessage 之后而不是直接在 onmessage 响应中做出实际响应。

像这样的:

let bestMove = null;
stockfish.onmessage = (e) => {
  let info = e.data ? e.data : e;
  if (info.includes('bestmove') || info.includes('ponder')) {
        bestMove = info.split(/ +/)[1];
        // set bestmove after calculating...
    }
}


(async function() {
  await stockfish.postMessage('go depth 15');
  // do the move after the message
  chess.move(bestMove);
  await stockfish.postMessage(`position fen ${chess.fen()}`);
})();

【问题讨论】:

  • 代码对于 async 和 await 来说似乎是正确的,它一定可以工作
  • 应该可以,请创建一个minimal reproducible example
  • stockfish 对象是什么,您能提供文档链接吗?它的.postMessage() 方法是否返回一个承诺?
  • 我用过这个,npmjs.com/package/stockfish。我不太确定它是否支持承诺,我还没有阅读它。
  • @JamesUrian 所以你在网络工作者中使用它?不,这些不支持承诺,您必须自己等待消息事件。参见例如herethere

标签: javascript


【解决方案1】:

await keyword 对您的代码没有任何影响,因为函数 stockfish.postMessage 不返回 Promise。 postMessage 发出一个将在下一个滴答声中处理的事件。这就是为什么在console.log('test2') 之后记录了console.log('test3')。发出事件后,它将同步返回,记录 console.log('test2')。

stockfish.onmessage 需要成为所有事件的控制中心。它需要了解不同的消息,并采取适当的行动。您不需要将操作的实施放在 onmessage 中。您可以创建一个函数并从 stockfish.onmessage... 调用它,然后在 action 函数中,如果您需要通知 stockfis 更改...等等,您可以调用 stockfish.postMessage ......等等。 ..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多