How to properly check and log http status code using promises and node.js?

我们两清 提交于 2019-12-02 01:30:52

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}`)
            }
        })
    })
}

Using util.promisify(), you can convert http.get() into a promise-based asynchronous method, but first there's some preparation to do since it does not follow the convention of callback(error, response) { ... }:

const http = require('http')
const { promisify } = require('util')

// define a custom promisified version of `http.get()`
http.get[promisify.custom] = (options) => new Promise(resolve => {
  http.get(options, resolve)
});

// convert callback to promise
const httpGet = promisify(http.get)

async function getStatusCodeResult(website) {
  const res = await httpGet(website)
  const status = res.statusCode
  const message = `${http.STATUS_CODES[status]}: ${website}`

  if (status >= 400) {
    throw message
  } else {
    return message
  }
}

In addition, you can use http.STATUS_CODES to get the the appropriate message for each possible statusCode rather than returning a vague Error or Success.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!