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

前端 未结 2 1098
孤城傲影
孤城傲影 2021-01-13 14:07

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 callba

2条回答
  •  心在旅途
    2021-01-13 14:54

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

提交回复
热议问题