【发布时间】: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 function 和 await keyword 不起作用?
为什么test2在test3之前先被记录,因为我使用的是异步函数,它应该工作,但它没有,这是为什么?
这是我处理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。我不太确定它是否支持承诺,我还没有阅读它。
标签: javascript