A
A
akdes2017-07-10 17:44:40
Asynchronous programming
akdes, 2017-07-10 17:44:40

How to make synchronous functionality on asynchronous node + vanilla JS?

Good afternoon.
I am writing a small program on an electron, at startup the program must do several operations with the server.
For all known reasons ("this will be faster", "no time to look at FW", etc.) I decided to write everything in pure JS.
So, I am friends with asynchrony and the concept of this technology. but I want to solve the starting functionality synchronously, i.e.:
this is how it works now:

app.on('ready', register)

function register() {
   doThis("abc", myCallback)
}

function myCallback(request, error...) {
   if(request.message == "foobar") {
      doThat("cba", otherCallback);
   }
}

function otherCallback(request, error...) {
  doSomething(request.foo);
}

and so you want:
app.on('ready', register)

function register() {
   var request = doThis("abc");
   if(request.message == "foobar") {
      var someVar = doThat("cba");
      console.log(someVar);
   }
}

For requests, I use request(options, callback)
At this stage, I work asynchronously, but I want to remake the starting functionality into synchronous, because already now I have 10 sub-functions that are created only for callbacks in order to simulate the synchronous flow of the program.
I am a PHP Developer, I have little experience in JS as a full-fledged language, in this regard, please explain / direct me how to force asynchronous functions like request, fs (filesystem) etc. make it work synchronously, more precisely, only when the answer is received - move on.
Thanks a lot

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolai Kargin, 2017-07-11
@kgnk

Use callbacks and promises .
Here , for example, about fs. You can immediately flip through the examples.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question