Home Function enters then before request completed
Reply: 0

Function enters then before request completed

user7983
1#
user7983 Published in September 20, 2018, 1:26 pm

My async function enters then before request is completed. Shouldn't Then part of the code executes only after the async function is completed? How to make the function call only when all the function has finished executing?

app.js

var request_test = require('./request_test');

baseUrl = "https://github.com";
promiseFunction().then((result)=>{
    console.log("complete")
});

var promiseFunction = async function promiseFunction() {
    request_test.request_test(baseUrl);
}

request_test.js

var request = require('request');
var cheerio = require('cheerio');

var request_test = function check(baseUrl) {
    console.log("baseUrl:" + baseUrl)
     var options = {
        url: baseUrl
     };
     request(options, function (error, response, html) {
        if (!error) {
           console.log("no error");
        }else{
        console.log("else js");
        console.log(error);
        }
      });
 }

module.exports = {
    request_test: request_test
};

share|improve this question
  • async has no magic powers to detect completion. If request_test.request_test(baseUrl); is an async function, then it must either return a promise that fulfills when the async operation is done or it must take a callback. If it returns a promise, then you can return that promise from the parent function and then you can use .then() on the parent function. It appears that you are expecting promiseFunction() to magically know when request_test.request_test(baseUrl); is done with its async operation. It doesn't know that. – jfriend00 Feb 14 at 7:49
  • Instead, you need to make request_test.request_test(baseUrl); return a promise that is linked to its async operation. Then, you can return that promise from promiseFunction() and then promiseFunction().then() will work properly. – jfriend00 Feb 14 at 7:50
  • Wasn't aware of the need for promise to ensure then works. Added the promise in the request_test module and await in promiseFunction and it works as desired. Thanks for pointing it out. – Stephen Paul Samynathan Feb 14 at 10:29

2 Answers 2

active oldest votes
up vote 1 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.288591 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO