Node.js http获取和返回statusCode

时间:2018-08-10 06:40:18

标签: node.js https

我想遍历网址列表,并检查它们是否有效(如果未返回404状态代码)。我的代码如下。但是我的数据对象中的isValid键似乎没有相应地填充。

var https = require('https');

const check = async url => {
  let result = false;
  try {
    const request = await https.get(url);
    result = request.statusCode !== 404;
  } catch (err) {
    console.log(err);
  }
  return result;
};


// and in another function, I am doing this
const data = [];
const urls = [/* urls here */];
urls.forEach(url => {
 data.push({
   url,
   isValid: await isValidUrl(url)
 })
});

1 个答案:

答案 0 :(得分:0)

您正在调用其他函数,请使用Promise.all获取数据。

var https = require('https');

const check = async (url) => {
    let isValid = false;
    try {
        const request = await https.get(url);
        isValid = request.statusCode !== 404;
    } catch (err) {
        console.log(err);
    }
    return {
        isValid,
        url
    };
};


// and in another function, I am doing this
const data = [];
const urls = [ /* urls here */ ];
const result = Promise.all(urls.map(url => check(url)))