node.js – How to wait for Restful API result in NodeJS


I work with a JSON API from Amazon, in which I search for products and treat the information according to its results, but inside NodeJS the API information is written in the console, but not written in the response to the call. How to respond only after data returned from Amazon?

Here's the code example:

var http = require("http");
//Biblioteca para conexão e pesquisa nos servidores da Amazon 
var aws = require("aws-lib");

http.createServer(function (req, res) {
    res.writeHead(200, {"Content-Type": "application/json"});
    var prodAdv = aws.createProdAdvClient(yourAccessKeyId, yourSecretAccessKey, yourAssociateTag);
    var options = {SearchIndex: "Books", Keywords: "Javascript"};
    var resposta = "";"ItemSearch", options, function(err, result) {
        resposta = result;
}).listen(1337, "");

PS: The parameters of the createProdAdvClient function were changed for security reasons, for all purposes they are filled.


AWS services are intrinsically Asynchronous. Of the two, either you adopt this paradigm or you must use a Node JS library or module that transforms from this asynchronous paradigm to a synchronous one.

If you want to use a synchronous paradigm then you can test with Step

A simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless.

Use the Serial Execution option

See an example below:

The Step function of the step module accepts any number of functions with their arguments and executes serially in order using this and passing to the new function in the next step.

  function readSelf() {
    fs.readFile(__filename, this);
  function capitalize(err, text) {
    if (err) throw err;
    return text.toUpperCase();
  function showIt(err, newText) {
    if (err) throw err;

Note that this is passed in the fs.readFile function. When the reading of the file finishes, the Step function sends the result as an argument to the next function in the chain. Then the value returned by capitalize is passed to showIt which displays the result.

With this we can synchronously chain the execution of the methods.

Scroll to Top