SadPanda
SadPanda

Reputation: 165

Set a Variable with a async function

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

Upvotes: 0

Views: 2379

Answers (1)

Thomas
Thomas

Reputation: 181785

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;
}

Upvotes: 1

Related Questions