-1
var http = require('http');
var qhttp = require('q-io/http');
var formidable = require('formidable');
var categories;

qhttp.read("https://api.myjson.com/bins/509wa")
 .then(function (json) {
  categories = JSON.parse(json).categories;
 })
 .then(null, console.error);


module.exports.putCat = function(req, res){

    var form = new formidable.IncomingForm();

    form.parse(req, function(error, fields, files){
        if(error){console.log(error)}
        fields["catProd"] = [];
        categories.push(fields);

        var dataString = JSON.stringify({categories: categories});
        console.log(dataString);
        var options = {
            host : "api.myjson.com",
            path : "/bins/509wa.json",
            method: "PUT",
            headers: {"Content-Type": "application/json", "Content-Length": dataString.length}
        };

        function callback(response){
            var body = "";
            response.on('data', function(chunk){
               body+=chunk; 
            });
            response.on('end', function(){
                console.log('Received data: '+body);
            });
        }

        http.request(options, callback).write(dataString);
        res.end();
    });
};

screenshot

It works perfectly with something like JSON.stringify("hello":"world");. However, when I tried with my data that needs to be stored (which is much longer), it doesn't send anything to the API. Thanks in advance!

Stanley Nguyen
  • 442
  • 3
  • 18

1 Answers1

0

You have a race condition with the categories variable. If some external code calls putCat() quickly after loading the module, then the categories data may not be available yet.

If you have async module loading things to do, then you should probably expose a module constructor which returns a promise and you can then do the putCat() after that promise resolves.

jfriend00
  • 683,504
  • 96
  • 985
  • 979