0

I am trying to create a helper function to create some token and use it in other functions. In the below functions: I intend to return the token and then print it. But it is printing before completing the function and hence there is not output. Not sure how to make it synchronous such that it will always finish the function before printing the output.

var response=""

function post_request(headers=build_request_headers(), request=build_request_object()){
    api = supertest(config.url+":"+ config.port)
    api.post(api_path.in_requests)
       .set(build_request_headers())
       .send(request)
       .then((res) => {
           response=res
       })
    return response
}
console.log(post_request())
aby
  • 95
  • 1
  • 11
  • 1
    have you tried fake api calls ? in most cases you don't need to do actual call. you need just prepare fake result. you can use sinon http://sinonjs.org/releases/v6.0.0/fake-xhr-and-server/ – Mini Jun 13 '18 at 23:30
  • First of all, it's a special case of http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call . A promise should be chained. Extracting a result from a promise will result in poor control flow. And then, this may be a problem in testing methodology. Persistent state between tests has a smell, and there's a chance that no real requests should be performed, as suggested in the comment above. – Estus Flask Jun 14 '18 at 02:34
  • I fixed the problem using async and await. Is that a better solution then chaining the promise? – aby Jun 15 '18 at 22:03

0 Answers0