嵌套的异步方法怎么返回一个值?

嵌套的异步方法怎么返回一个值?,第1张

嵌套的异步方法怎么返回一个值?,第2张

puppeteer 官方文档里的一段代码想改一下 https://pptr.dev/#?product=Puppeteer&version=v7.0.1&show=api-pagewaitforselectorselector-options

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  let currentURL;
  page
    .waitForSelector('img')
    .then(() => console.log('First URL with image: ' + currentURL));
  for (currentURL of ['https://example.com', 'https://google.com', 'https://bbc.com']) {
    await page.goto(currentURL);
  }
  await browser.close();
})();

简单的 print 第一个有 img 的网站。想改成

const puppeteer = require('puppeteer');

const get_available_item = async (page) => {
  let currentURL;
  const urls = [
    'https://example.com',
    'https://example.com',
    'https://baidu.com'
  ]
  page.waitForSelector('img').then(
    () => {
      console.log('First URL with image: ' + currentURL)
    }
  );
  for (currentURL of urls) {
    await page.goto(currentURL, {waitUntil: 'load'});
  }
};

const main = async () => {
  const browser = await puppeteer.launch({
    headless: false,
    product: 'firefox',
    defaultViewport: { width: 1366, height: 768 }
  });
  
  const page = await browser.newPage();
  await get_available_item(page)
  await browser.close();
}

main()

想让get_available_item返回currentURL,试了一种用 callback 返回的方法

const puppeteer = require('puppeteer');

const get_available_item = async (page, callback) => {
  let currentURL;
  const urls = [
    'https://example.com',
    'https://example.com',
    'https://baidu.com'
  ]
  page.waitForSelector('img').then(
    () => {
      callback(currentURL)
    }
  );
  for (currentURL of urls) {
    await page.goto(currentURL, {waitUntil: 'load'});
  }
};

const main = async () => {
  let url
  const browser = await puppeteer.launch({
    headless: false,
    product: 'firefox',
    defaultViewport: { width: 1366, height: 768 }
  });
  
  const page = await browser.newPage();
  await get_available_item(page, (res) => {
  	url = res
  })
  console.log(`result is ${url}`)
  await browser.close();
}

main()

有比 callback 更简洁的方法么?

----------------------- 以下是精选回复-----------------------

答:试试用订阅发布模型。

window.addEventListener('getWithImageUrl', (_url) => url = _url); window.dispatchEvent(new Event('getWithImage'))
答:能在你想返回的地方加点注释吗。。
答:既然已经用 async 了,把 callback 改成 promise 后用 await
答:你都用 async await 了还不会包装个 Promise 吗,返回值 <string>Promise
答:const get_available_item = async (page: string):Promise<string> => {
return new Promise<string>( ( reject) =>{
// ...
reject(currentURL)
})
}

const currentURL = await get_available_item(page)
答:啊哈,脑抽写错了··· 不过不影响···· lz 自己改成 resolve 吧

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » 嵌套的异步方法怎么返回一个值?

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情