在我的小程序中,我尝试取消缩短 URL,然后检查链接是否与我的模式匹配。如果确实如此,我想进一步处理它。但我还需要应用之前已知的 3 个参数。
将所有 3 个参数拖到每个函数中时,我的代码感觉非常笨重。在没有 promise 的情况下我怎样才能简化这个过程?
var request = require("request");
function expandUrl(shortUrl, a,b,c, callback) {
request( { method: "HEAD", url: shortUrl, followAllRedirects: true },
function (error, response) {
callback(response.request.href, a,b,c);
});
}
function checklink(unshortenedLink, a, b, c){
matches = unshortenedLink.match(/twitter\.com\/\w+/g);
if(matches){
matches.forEach(function(result){
process_twitter_link(result, a, b, c);
});
}
}
function process_twitter_link(link, a, b ,c ){
console.log(link + " " + a + " " + b + " " + c);
// std.out: twitter.com/StackJava param_a param_b param_c
}
expandUrl("https://t.co/W0DA8WVpmO", "param_a", "param_b", "param_c", checklink);
最佳答案
由于您的问题出在回调中并且存在异步性,因此我建议使用 Promises:
function expandUrl(shortUrl) {
var deferred = Deferred.create();
request( { method: "HEAD", url: shortUrl, followAllRedirects: true },
function (error, response) {
deferred.resolve(response.request.href,);
});
return deferred.promise();
}
expandUrl(shortenedUrl).done(function (resolved_url) {
checklink(resolved_url, "param_a", "param_b", "param_c");
});
这会从 expandUrl
中删除 3 个参数,但它们仍保留在 checklink
上。
我不确定 Node.js 是否有 Promise 模块。 request
可能会返回一个本身的 promise 。您也许可以链接 .then
并以这种方式仅返回已解析的 url。
没有 promise :
function expandUrl(shortUrl, callback) {
request( { method: "HEAD", url: shortUrl, followAllRedirects: true },
function (error, response) {
callback(response.request.href);
});
}
expandUrl(shortenedUrl, function (resolved_url) {
checklink(resolved_url, "param_a", "param_b", "param_c");
});
关于javascript - 在没有 promise 的情况下将多个参数应用于回调 - node-js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19815706/