How to wait for the result of a Restful API in NodeJS

5

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

Here is 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 = "";
    prodAdv.call("ItemSearch", options, function(err, result) {
    console.log(result);
        resposta = result;
    });
    res.end(resposta);
}).listen(1337, "127.0.0.1");

PS: The parameters of the createProdAdvClient function have been changed for security purposes, for which purpose they are all filled in.

    
asked by anonymous 23.02.2014 / 20:18

2 answers

3

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

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 function Step of the module step accepts any number of functions with its arguments and executes serially in order using the this and moving to the new function in the next step.

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;
    console.log(newText);
  }
);

Note that the this is passed in the fs.readFile function. When reading the file ends the function Step sends the result as argument to the next function of the string. 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.

    
25.02.2014 / 01:16
1
prodAdv.call("ItemSearch", options, function(err, result) {
console.log(result);
    resposta = result;
});
res.end(resposta);

Did you mean: (I simplified the code and fixed the error using link )

prodAdv.call("ItemSearch", options, function(err, result) {
  if (err) {throw err;}
  console.log(result);
  res.write(result);
  res.end();
});
    
23.02.2014 / 20:54