首页 > 解决方案 > 通过 URL 发布请求的 Asnyc 循环

问题描述

我正在尝试异步遍历一堆 URL,但是我发现虽然这种方法通常可以使用axios.get(url)它,但当我使用 post 方法尝试它时,它却返回 undefined。

有谁知道为什么会出现这种情况 - 或者在发出帖子请求时有更好的异步循环一堆页面的方法?

const axios = require('axios');

let data = [];
let promises = [];

// 1. Import URLS
const urls = ['https://example.com/',
              'https://example.com/page-a.html',
              'https://example.com/page-b.html'];

// 2. Queue up the promises
urls.map(function(url) {
  promises.push(
    axios.post(`https://chromeuxreport.googleapis.com/v1/records:queryRecord?key=${API_KEY}`, {
      url: url,
      metrics: ["first_contentful_paint",
                "first_input_delay",
                "largest_contentful_paint",
                "cumulative_layout_shift"],
      effectiveConnectionType: '4G',
      formFactor: 'ALL_FORM_FACTORS'
    })
  )
});

// 3. Return the responses
axios.all(promises).then(function(results) {
    results.map(function(res) {
      try {
        const { key, metrics } = res.record;
        console.log(metrics);
      }
      catch(e) {
        console.error(e);
      }
    })
});

标签: javascriptnode.jsaxios

解决方案


推荐阅读