【问题标题】:Set a Variable with a async function使用异步函数设置变量
【发布时间】:2020-01-21 19:27:35
【问题描述】:

我有一个节点项目,我想用一个生成异步内容的函数的返回值填充一个 var:

index.js

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

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

    }
})();

搜索.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;
    } );
}

输出:

未定义

【问题讨论】:

标签: javascript node.js


【解决方案1】:

您正在使用await search.searchMU(),但searchMU 没有返回承诺。另外,如果可以在任何地方使用await,为什么还要使用显式的承诺链样式(.then(...))?

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 2020-04-16
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多