javascript synchronous callbacks

时间:2016-06-10 16:11:40

标签: javascript synchronization

I'm looking to see if there is a way of taking a generic async function, such as AJAX, or web worker on message, and forcing it to behave synchronously.

First off - I really do need this behaviour, I am aware of all the arguments regarding async callbacks vs returns - but in this case, I truly need to wait for a callback.

If there is no generic solution available I'd settle for one that works purely on the Worker.prototype.onmessage as that is the primary use case here.

I'm fairly sure the answer will be "thats not possible" but I wanted to check before surrendering.

I've already looked into promises and generators, I'd prefer not to use a third party library (I'm aware of fiber/futures for Node).

A potential use case:

function main(){
    worker = new Worker("someWorker.js")
    var result = worker.onmessage(function(event){
        return event.data;
    })
    //wait for worker.onmessage
    return result;
}

1 个答案:

答案 0 :(得分:-1)

如果要保留同步功能流,则生成器功能是唯一可行的解​​决方案。您将发送所有异步任务,例如var result = yield new Worker('someWorker.js')

function* main之外,您将获得worker mainFn.next().value,然后附加onmessage侦听器,将已解析的数据返回function* main并执行此功能将恢复。

完整的生成器示例如下所示

// write function as generator
function* main () {
    var result = yield new Worker("someWorker.js");
    return result;
}

// instantiate the generator and get the first yield value
var mainFn = main()
  , worker = mainFn.next().value

// set onmessage listener, which is callback, that sends data back to *main()
worker.onmessage = function(event) {
    mainFn.next(event.data);
}

这样你的main()函数将保持与原始形式几乎相似,因此你可以重用原始代码,但是你需要编写周围的逻辑,这不是简单的,无论如何都会使用回调。 / p>

您似乎意识到什么是生成器,并且它在浏览器中没有得到广泛支持,因此如果您想在网页上运行此代码,则需要ES6转换器Babel