Wednesday, 19 April 2017

How to return the output of an asynch function to a doGet() function

I have a situation where I want to return the output of an asynchronous test via an httprequest and then pass the result to later be displayed in the browser. The problem I am having is that my function doThis() returns before the asynchronous function test() completes.

  1. How can I make doThis() "wait" until test() is done before returning back to my get() function?
  2. The output of test() is currently going to the stdout and stderr. How can I capture the response and then return it as a string, buffer, etc. as the return value of doThis()?

Original Application

var other = require('/other.js');

app.get('/myUrl', function(req, resp) {
  var cmd = 'CmdText';
  var respText = other.doThis(cmd);

  resp.status(200).send(respText);
  return;
};

other.js

 var tape = require('tape');
 var _test = require('tape-promise');
 var test = _test(tape);

 module.exports.doThis = function(cmd) {
   test('First and only test', function(t) {
     myMethod(t, cmd).then(function() {
       t.pass('Good');
       t.end();
     },
     function(err) {
       t.fail('Bad');
       t.end();
     });
   });

   return something;
 };



via Eric M. Brown

No comments:

Post a Comment