简体   繁体   中英

Get result out of JavaScript's Promise synchronously

I have an API (outside my control) that returns a Promise . I'd like to get the value out of a Promise in a synchronous manner and hide the async-ness of the API, ie without bubbling up async / await , .then(...) s and so on.

In other words, I am looking for the JavaScript equivalent of C#'s Task<TResult>.Result .

Thanks!

This is not possible. The only way to really block the execution of other code is something like

while (true) {
  // break on some condition - i.e. after 5 second or when you find that something happened
}

Which means that you run synchronous task (like while cycle) that has to run and never stop (=use 100% of processor time).

Also it blocks only the Event Loop (which is something that executes all your code), but if there is some task assigned to worker thread, it still be executed in that thread.


You should write what is your use case, how have you tried to approach it. Your question seems like you probably do not have enough understanding of how Node.js work. There is nothing wrong with the "asynchronicity". Its even more simplier than in other languages - there is only one thread for that event loop = there are no problems with synchronizing the threads, race conditions etc. (at any moment, the code you have written is executed by exactly one thread and it always have to finish the whole synchronous part before "asynchronously" jumping for another task - its very deterministic and predictible)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM