我对 JavaScript 很陌生,对 Node.js 框架也很陌生,几天前才开始使用它。如果我的代码是无意义的,我很抱歉,承诺和回调的整个想法仍然深入人心。话虽这么说,我的问题如下,我试图根据以下范围确定对网站的某些请求是否成功或导致错误他们的状态代码响应。我正在与一系列网站合作,到目前为止我所做的工作如下,但是我确实得到了TypeError: Cannot read property 'then' of undefined
在我安装了 node.js 的本地计算机上,但不明白为什么。
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
弄清楚代码是否有效。
// Example Printout
{
success: ['https://www.google.com/', 'https://www.spotify.com/us/',
'https://twitter.com /' ],
error: [''http://google.com/nothing']
}
你混淆了前两行。这new Promise
为您提供返回值的包装器需要位于外部,并且http.get
调用应该在其执行器回调内部。而且你真的不需要超时:
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}`)
}
})
})
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)