-1

So I've got a working node.js code that processes data from a website's API. I'd like to speed it up a bit and I figured the best way to do that would be to send a request and while waiting for a response some code would execute and not just wait for a response like it is now. Right now my code is essentially this:

function httpGet(url){
  var response = requestSync(
    'GET',
    url
    );
    return response.body;
}

var returnCode;
var getUrl = "url"
returnCode = httpGet(getUrl);
var object = JSON.parse(returnCode);

//Some code executes

As you can see with this way some time is lost because you're waiting for the response. I'd be looking for something in this sense (pseudocode):

  1. Send a request
  2. Some code that's not related to the request is executed right after the request is sent
  3. After the part above is done the request result is parsed

In conclusion I'm looking for a way to send a request and not waste time waiting for a response. If you have any other ideas on how to speed up the code please let me know :)

quo91
  • 139
  • 1
  • 1
  • 13

1 Answers1

2

You are looking for asynchronous code. When you use a function like requestSync it means that it "blocks" until it's done. It's synchronous. When you use something asynchronous, you will usually do so with a callback (a function to call when the desired action is completed) or a promise (an abstraction over callbacks). There are lots of questions about using those on SO. This post: How do I return the response from an asynchronous call? has a bunch of info related to your question.

ktilcu
  • 3,032
  • 1
  • 17
  • 15