red_student red_student - 3 months ago 11
Javascript Question

get JSON from a Promise

I am using mocha to test a promise that is written in a separate javascript file. I am trying to send data to the promise with a POST request, although I'm not sure what the url should be. Here's what I have so far, using request-promise:

var rp = require('request-promise');
var options = {
method: 'POST',
url: '/algorithm.js',
body: data,
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function(body){
count++;
done();
});


The error states that I have an invalid url, although I'm not sure how else to POST to promise inside of a javascript file.

Answer

I am trying to send data to the promise with a POST request

You can't do that, at least not directly.

  • POST requests are for sending data to HTTP servers.
  • Promises are a JavaScript object for handling asynchronous operations.

These are different things.

algorithm.js needs to either contain code that you can call directly, in which case you should require that code and then call the function.

var algorithm = require("algorithm");
if (algorithm.something()) {
    count++;
}
done();

… or it should be server side JavaScript that you need to run an HTTP server for. Once you run the HTTP server, you'll be able to use code like what you wrote in the question, but you'll need to provide an absolute URL since you need to say you are using HTTP and localhost and so on.

var options = {
    method: 'POST',
    url: 'http://localhost:7878/route/to/algorithm',
    body: data,
    json: true // Automatically stringifies the body to JSON 
};
Comments