在同步功能中等待Promise.all,基本上是阻塞的!javascript [英] wait for Promise.all in a synchronous function, basically blocking! javascript

查看:118
本文介绍了在同步功能中等待Promise.all,基本上是阻塞的!javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在基本ajax请求之前,我有很多要执行的同步函数,这些请求会将html呈现为DOM.

I have alot of syncrhounous functions that i want to execute before that are basic ajax requests, these request will render html to the DOM.

为了做到这一点,我必须执行所有这些同步一一请求.但是我不知何故想要这些异步功能同时全部异步,并等待它们完成以加快处理速度.这必须在同步函数内部进行.但是我的理解是,这在javascript中不起作用,但是我想听听你们必须说些什么.

In order to do this i had to execute all of this synchrounous requests one by one. But i somehow want to these synchrounous functions asynchrounous all at the same time and wait for them to finnish in order to speed things up. This has to happen inside a synchrounous function. But my understanding is that this doesnt work in javascript, but i would like to hear what you guys have to say.

所以我的尝试是将所有这些同步请求添加到异步承诺中,然后进行Promise.all调用.我等不及promise.all().然后,因为在这个主要的同步线程/函数之后,主线程将继续执行其余代码.所以我想知道是否有一种方法可以阻塞主线程,以便等待这些异步调用

So my attempt was to add all of these synchrounous requests into asynchrounous promises and then do a Promise.all call. I cant wait for the promise.all().then because the main thread will keep on execute the rest of the code after this main synchrounous thread/function. So i wonder if there is a way to block the main thread in order to wait for these asynchrounous calls

这是我在说什么的简短说明

heres a short illustration of what im talking about

var syncfunc = () => {
var getPromise = () => {
    return new Promise((resolve) => {
        var asyncAjaxRequest = async function() {
            doSomeStuff();
            resolve();
        }
    })
}
var promises = [getPromse(), getPromse(), getPromse()];


Promise.all(promises);

console.log('i want this console.log to execute after all promises executed doSomeStuff');

/**
 * 
 * Promise.all(promises).then(() => {
        // I cant use this, because its script in other files that will execute if i wait like this
    })
 */
}

我知道.then将在所有解析完成后执行,但是我非常想阻止这个同步线程,等待所有其他异步完成.

I know .then will execute when all resolves are done, but i basiacally want to block this synchrounous thread waiting for all other asynchrounous to finish.

如果可以的话,我当然可以将结构更改为我的需要,但是问题和我尝试这样做的原因是因为我正在使用sitevision框架,并希望在打印模块打开前将一些内容添加到dom中.打印窗口.同步调用每个函数并不是走的路,它很慢.Ive还尝试将window.print = null设置为禁用打印功能,然后在promises解析后将打印功能重新添加回去,但这根本不起作用

If i could i would ofcourse change the structure into my needs, but the problem and the reason why im trying to do this is because im using sitevision framework, and want to add some content to the dom before a print module opens the print window. To call every function synchrounous is just not the way to go, its to slow. Ive also tried to set window.print = null to make the print function disabled, and then add the print function back when promises resolves, but it simply doesnt work

推荐答案

您不能使用纯Javascript(没有外部代码)将异步操作转变为同步操作.事件驱动的JS引擎无法正常工作.

You cannot make an asynchronous operation turn into a synchronous one in plain Javascript (without external code). The event driven JS engine just doesn't work that way.

根据定义,异步操作将开始该操作(将执行移交给本机代码),然后返回到解释器,然后解释器将继续执行随后的代码.完成后,本机代码会将事件添加到JS事件队列中,以允许解释器事件循环为异步操作的完成提供服务.如果您正在创建某种块",例如半无限的while循环,那将阻止"解释器执行更多代码,那么您将陷入僵局.阻塞解释器的循环阻止JS解释器到达可以处理表示异步操作结束的事件的地步.因此,您有一个循环在等待某件事完成,但是等待的事情要等到该循环结束才能完成-僵局.

By definition, an asynchronous operation starts the operation (handing execution off to native code) and then returns back to the interpreter which then continues to execute the code that follows. The native code will add an event to JS event queue when it finishes to allow the interpreter event loop to service the completion of the asynchronous operation. If you were the create some sort of "block" such as a semi-infinite while loop, that would "block" the interpreter from executing more code, you end up in a stalemate. The loop that is blocking the interpreter prevents the JS interpreter from ever getting to the point where it can ever process the event that signals the end of the asynchronous operation. So, you have a loop waiting for something to finish, but the thing it's waiting for can't finish until the loop finishes - stalemate.

因此,由于JS解释器的单线程事件循环性质,您(纯粹在Javascript中)不能阻止等待异步操作的结束.

So, because of the single threaded event loop nature of the JS interpreter, you can't (purely in Javascript) block waiting for the end of an asynchronous operation.

通常,正确的设计是重构周围的代码/基础结构,以使其与异步操作和异步结果(回调或Promise)一起使用.

Pretty much always, the correct design is to refactor the surrounding code/infrastructure to work with an asynchronous operation and asynchronous result (callback or promise).

如果这是node.js,那么有几个可怕的骇客可以为您提供此结果,但是它们会阻塞整个解释器,因此几乎永远不会是您想要的设计.

If this is node.js, there are a couple of horrific hacks that can get you this result, but they block the entire interpreter so are almost never a desired design.

第一个选项涉及编写一个自定义的nodejs插件(以本机代码完成的异步操作),该插件提供一个阻塞接口,该接口直到操作完成才返回.

The first option involves writing a custom nodejs plugin (async operations done in native code) that provides a blocking interface that just doesn't return until the operation is done.

第二个选项涉及使用同步child_process操作(例如child_process.execFileSync()创建一个阻塞的子进程,在该子进程中运行您的代码,然后在该进程完成时继续执行.

The second option involves using the synchronous child_process operations (such as child_process.execFileSync() to create a blocking child process, run your code in that child process and then continue when that process finishes.

我都可以考虑非常糟糕的hack,几乎从来都不是解决此类问题的理想方式.但是,我确实想向您展示为了阻止异步操作(必须将其移出Javascript或移出进程)必须执行的操作.

Both I could consider pretty bad hacks and pretty much never the desired way to solve such a problem. But, I did want to show you what has to be done in order to block for an asynchronous operation (it has to be moved out of Javascript or out of the process).

如果您不知道如何使用非阻塞的异步操作解决实际问题,建议您发布一个新问题,在其中详细描述真正的问题是什么,我们可以帮助您找到异步设计将适合您的情况.如果您在此处的评论中张贴了指向新问题的链接,则从事此活动的某些人可能会检查新问题并尝试提供帮助.

If you can't figure out how to solve your real problem with non-blocking, asynchronous operations, I'd suggest you post a new question where you describe in detail exactly what the real problem is and we can help you find an asynchronous design that would work for your situation. If you post a link to the new question in a comment here, some of the people engaged here may check in on the new question and attempt to help.

这篇关于在同步功能中等待Promise.all,基本上是阻塞的!javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆