【问题标题】:Handling asynchronous function with webworker and promise使用 webworker 和 promise 处理异步函数
【发布时间】: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


【解决方案1】:

你有一个错误的语法来解决你的承诺。

.then 接受一个函数回调,当 promise 被解析时调用。

所以在你的情况下这个代码:

// Call asyncFunc : blocking ???
asyncFunc(HitCurrent).then(console.log('Call async function'));
// Prove asynchronuous of asyncFunc call
alert('after asynFunc().then');

应该是:

asyncFunc(HitCurrent).then(() => alert('after asynFunc()'));

为了以“同步方式”编写代码,您可以这样使用async/await

function asyncFunc(HitCurrent) {
  // Return promise
  return new Promise(resolve => {
    setTimeout(() => resolve('finished'), 1000);
  }).then(data => {
    alert('promise resolved:' + data);
  })
}

(async () => {
  await asyncFunc();
  alert('after asynFunc().then');
})();

因此,您创建了一个异步函数,该函数等待您的承诺得到解决,然后提醒值。

【讨论】:

  • 好的,谢谢!我要试试你的解决方案。但是为什么 -@Patrick Roberts 告诉我在我的情况下这是不可能的?问候
  • 我认为他理解你不想简单地编写你的代码,如果它看起来同步,但你真的希望代码将在操作系统级别同步执行。但也许问他是最好的办法:)
  • 好的,它按预期工作!真的谢谢。如果我理解得很好,我们可以使用(async) 和await asyncFunc 来绕过这个问题:所以(async () =&gt; { await asyncFunc(); alert('after asynFunc().then'); })(); 的部分是阻塞的,我的意思是,等待所有asyncFuncfunction 的执行,不是吗?
猜你喜欢
  • 2014-09-28
  • 2021-06-28
  • 2021-08-03
  • 2021-02-15
  • 2020-08-13
  • 2019-04-01
  • 2018-10-15
相关资源
最近更新 更多