JavaScript-同步等待异步操作(休眠) [英] JavaScript - sync wait for async operation (sleep)

查看:562
本文介绍了JavaScript-同步等待异步操作(休眠)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它在这里被问过很多次,而且回答过很多次,这不是应该怎么做,而是再一次:)

I know it was asked here many times and many times answered this is not a way how it should be done, but once more again :)

是否可以通过某种方式调用异步功能(例如计时器/ajax调用),基本上是常见的异步任务并同步等待直到其结束而没有100%CPU使用率和浏览器阻塞?

Is it possible, somehow, to call async function (such as timer / ajax call), basically common async task and synchronously wait until it ends without having 100%CPU usage and blocked browser?

简单的答案就足够了-是或否.如果没有,我必须以异步方式"根据异步操作编写所有代码,否则会更好;)

Simple answer is enough - yes or no. If no i have to write all code depending on the async operation in "async way" Otherwise, it would be better ;)

想象一下:

updateCSS("someurl.css")

function updateCSS(url) {

   var css = getCachedResource(url);

   css = css.replace(/regexp/gm, function(curUrl) {
     base64 = atob(getCachedResource(curUrl))
     return "data:image;base64," + base64
   })

}

function getCachedResource(url) {
  
  //...
  
  if (cached) {
    
    return cached
    
  } else {
    
    // doajax...    
    // watfor
    
    return loaded
  }
  
}

当然,我可以使它异步,但是代码将很糟糕.此外,我必须使调用此函数的所有函数异步.您能看到简单的解决方案吗?我会说封锁是最简单的.

Of course, I can make it async, but the code will be.... terrible. Moreover, I have to make async all functions calling this function. Can you see simple solution? Blocking would be simplest I would say.

谢谢

推荐答案

,即使CPU使用率达到100%或浏览器被阻止,您也无法做到这一点.事情经过精心设计,可以防止您这样做.

No, you can't do that even with 100% cpu usage or a blocked browser. Things have been precisely engineered to prevent you from doing that.

这使得所有异步代码都是有毒的,这意味着所有调用异步函数(基于Promise或基于回调的代码)的代码本身都必须是异步的.

This makes all asynchronous code is poisonous, meaning all code that calls async functions (either promise or callback based) must be asynchronous itself.

关于可怕的代码:Promise链和async/await用于救援,它们可帮助您编写语法更好的异步代码. 不要害怕,请使用async/await,特别是如果您已经使用了Transpiler.

About the terrible code: Promise chains and async/await for the rescue, they help you to write asynchronous code with much better syntax. Don't be afraid, use async/await especially if you already use a transpiler.

这篇关于JavaScript-同步等待异步操作(休眠)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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