我正在尝试编写一些代码,该代码将包含一个包含部分 URL 的字符串google.com
,并将它们转换为一个完整的 URL,如https://google.com
.
我对 Node.js 非常缺乏经验,而且我仍在尝试理解异步的想法。
我正在尝试使用回调而不是像 promises 和 async/await 这样的东西,在我的脑海中,以下代码应该可以工作:
exports.rectifyDocumentURLs = function(baseUrl, document, callback) {
callback(null,
document.replace(url_patterns.any, (match) => {
return exports.fixUrl(match, baseUrl, (err, res) => {
if (err) {
callback(err, null)
}
return res
})
})
)
}
url_patterns.any
是一些匹配任何类型代码的正则表达式代码,函数exports.fixUrl
是一个函数,它将获取部分 URL 并以完整形式返回它。
当我像这样运行代码时
exports.rectifyDocumentURLs("https://google.com", "google.com", (rectifyErr, rectifyRes) => {
console.log(rectifyRes)
})
当前的代码只是返回undefined
,但res
该的fixUrl
函数返回正确的结果,http://google.com
。
我知道这很像这里的许多问题,但经过广泛的研究和多次尝试和重写,我相信这可能是修复代码的唯一方法。
任何帮助将不胜感激。
你的功能rectifyDocumentURLs()
都搞砸了。
回调的想法是什么时候异步发生,你不知道什么时候完成。所以你传递给它一个函数,当它完成时,它调用你传递给它的函数,并得到你想要的结果。通常,接受回调的函数永远不会返回有意义的值——该值被传递给回调。在rectifyDocumentURLs()
您立即调用回调,然后使用另一个函数的回调再次调用它并返回一个(可能未定义的)值。那是行不通的。
这是一个更标准的方法:
exports.rectifyDocumentURLs = function(baseUrl, document, callback) {
// it looks like document.replace is async and takes a callback
// when it's done it will pass its result to the callback as match
document.replace(url_patterns.any, (match) => {
// you don't need return the result of a function that takes a callback
// it will pass its result to the callback
exports.fixUrl(match, baseUrl, (err, res) => {
if (err) {
callback(err, null)
} else {
// now that you have res and no error, call the callback
// you passed to rectifyDocumentURLs()
// this value will be the rectifyRes in the function you passed
callback(null, res)
}
})
})
}
当然,正如其他人指出的那样,已经有很多处理 URL 的现有代码,但这是一个很好的练习。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句