如何使用Promise和Node.js正确检查和记录HTTP状态代码? [英] How to properly check and log http status code using promises and node.js?

查看:55
本文介绍了如何使用Promise和Node.js正确检查和记录HTTP状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JavaScript的新手,也是Node.js框架的新手,几天前才开始使用它。我很抱歉,如果我的代码是荒谬的,promise和callbacks的整个思想仍然沉没。我要说的是以下问题,我试图根据对网站的范围来确定对网站的某些请求是否成功或导致错误他们的状态码响应。我正在与一系列网站合作,到目前为止,下面是我做的事,但是我得到了 TypeError:无法在本地读取未定义属性'then

I am new to JavaScript and very new to node.js framework, just started using it a few days ago. My apologies if my code is nonsensical, the whole idea of promises and callbacks is still sinking in. That being said my question is the following I am trying to figure out if certain request to websites are successful or cause an error based on the range of their status code response. I am working with an array of websites and what I've done so far is below, I do however get a TypeError: Cannot read property 'then' of undefined on my local machine with node.js installed and can't figure out why.

const sample = [
    'http://www.google.com/',
    'http://www.spotify.com/us/',
    'http://twitter.com/',
    'http://google.com/nothing'
]

const http = require('http')

const getStatusCodeResult = (website) => {

    http.get(website, (res) => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                let statusCode = res.statusCode
                error = statusCode >= 400 && statusCode <= 500 ? `error: ${website}`: null
                if (error) {
                    reject(error)
                    
                } else if (statusCode >= 200 && statusCode <= 300) {
                    resolve(`Success: ${website}`)
                }
            }, 0)
        })
    })
}
// LOOP PROMISES
const getAllStatusCodeResult = (websites) => {
    websites.forEach((website) => {
        getStatusCodeResult(website)
            .then((result) => {
                console.log(result)
            })
            .catch(error => {
                console.log('error', error)
            })
    })
}
getAllStatusCodeResult(sample)

希望将结果打印为以下示例,但是现在我仅使用 console.log 来确定代码是否有效。

Ideally I would want the result to be printed as the example below, but for now I am just using console.log to figure out if the code even works.

   // Example Printout
   {
      success: ['https://www.google.com/', 'https://www.spotify.com/us/', 
      'https://twitter.com /' ],
      error: [''http://google.com/nothing']
   } 


推荐答案

您混合了前两行。 新的Promise 包装器(需要返回值)位于外部,并且 http.get 调用应该在其执行程序回调中。另外,您实际上并不需要超时:

You mixed up the first two lines. The new Promise wrapper that gets you the value to return needs to be on the outside, and the http.get call should be inside its executor callback. Also you don't really need that timeout:

function getStatusCodeResult(website) {
    return new Promise((resolve, reject) => {
        http.get(website, (res) => {
            let statusCode = res.statusCode,
                error = statusCode >= 400 && statusCode <= 500 ? `error: ${website}`: null
            if (error) {
                reject(error)
            } else if (statusCode >= 200 && statusCode <= 300) {
                resolve(`Success: ${website}`)
            }
        })
    })
}

这篇关于如何使用Promise和Node.js正确检查和记录HTTP状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆