【发布时间】:2019-05-27 16:11:30
【问题描述】:
当我调用下面代码 sn-p 中定义的 asyncFunc 时,我尝试处理 promise 的返回以获得阻塞行为。在这个函数中,我使用的是 webworker。
我不是 JavaScript 专家,promise 的概念对我来说是新的。我试图在我的代码块中定义一个asyncFunc 函数。如果我之后调用这个函数,我通常应该完全执行 asyncFunc 中的代码(但我不确定)。
目标是在此处webworker 收到要绘制的数组 (HitCurrentvariable) 后在画布(当前代表游戏板)中绘制,即以同步方式(绘制函数为由displayCurrentHit(HitCurrent)执行)。
else if (mode == 'computer') {
// Call asynchronous function with promise
function asyncFunc(HitCurrent) {
// Return promise
return new Promise( resolve => {
// Creation of webworker
let firstWorker = new Worker(workerScript);
firstWorker.onmessage = function (event) {
resolve(event.data);
}
// Post current copy of HitCurrent, i.e HitCurrent
firstWorker.postMessage([HitCurrent, HitCurrent.playerCurrent, maxNodes]);
}).then(({result}) => {
// Get back game board of webworker
HitCurrent = result.HitResult;
// Get back suggested hit computed by webworker
[a,b] = HitCurrent.coordPlayable;
console.log('Into promise : coordPlayable : (a,b) = ',a,b);
// Drawing all lines from suggested hit (in 8 directions)
for (k = 0; k < 8; k++) {
exploreHitLine(HitCurrent, a, b, k, 'drawing');
}
// Remove playable hits
cleanHits('playable', HitCurrent);
// Display current game
displayCurrentHit(HitCurrent);
// Up to there, first computer hit is good
// and game board is well drawn
alert('Stop just after displayCurrentHit');
})
}
// Call asyncFunc : blocking ???
asyncFunc(HitCurrent).then(console.log('Call async function'));
// Prove asynchronuous of asyncFunc call
alert('after asynFunc().then');
}
asyncFunc 的调用没有阻塞。如何使用Promise 概念以同步方式显示当前游戏板?
【问题讨论】:
-
您可能会考虑在编写代码时使用一致的缩进 - 这将使阅读和调试变得更加容易,不仅对于潜在的回答者,而且对于您来说,当我们都可以看到
{}块及其嵌套级别一目了然。 -
@CertainPerformance 。抱歉,我只知道缩进代码的快捷键CTRL+K。
-
async函数不会阻塞。 -
.then(console.log('Call async function'))然后期望一个函数作为参数调用。您所做的是立即调用console.log('Call async function')并将结果(undefined)传递给.then() -
你真的在每个游戏动作中都实例化一个新的 webworker 吗?并且从未摧毁它?
标签: javascript asynchronous promise blocking