0

I have a node project, I want to populate a var with the return value of a function that make async stuff :

index.js

const search = require( './search.js' );

(async () => {
    try {
        var test =  await search.searchMU('test');
        console.log(test);
    } catch (e) {

    }
})();

Search.js

const puppeteer = require( 'puppeteer' );
exports.searchMU = function( searchInput ) {
    const fullUrl = url + excludes + type + display + search + searchInput;
    puppeteer.launch().then( async browser => {
      const page = await browser.newPage();
      await page.goto( fullUrl );
      var html = await page.content();
      await browser.close();
      return html;
    } );
}

Output :

undefined

SadPanda
  • 135
  • 7
  • 3
    `searchMU` doesn't return anything, add a `return` statement before `puppeteer.launch....`. – Titus Sep 20 '19 at 18:23
  • https://stackoverflow.com/questions/47789093/await-for-asynchronous-function-results-in-undefined – SadPanda Sep 20 '19 at 18:26

1 Answers1

1

You're using await search.searchMU() but searchMU does not return a promise. Also, why use explicit promise chaining style (.then(...)) if you can use await everywhere?

exports.searchMU = async function( searchInput ) {
    const fullUrl = url + excludes + type + display + search + searchInput;
    const browser = await puppeteer.launch()
    const page = await browser.newPage();
    await page.goto( fullUrl );
    var html = await page.content();
    await browser.close();
    return html;
}
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • Thank you I did like the doc : https://pptr.dev/#?product=Puppeteer&version=v1.20.0&show=api-class-puppeteer – SadPanda Sep 20 '19 at 18:29