我有以下代码
var getUrl = function(callback) {
ref.once('value')
.then(function(snap) {
let article_url = snap.val();
console.log(article_url);
callback(null, article_url); // I dont want to throw an error, so I pass null for the error argument
});
};
var getImage = function(err, data, callback) {
//if (err) throw err; // Check for the error and throw if it exists.
textapi.extract({
url: data,
best_image: true
}, function(error, response) {
if (error === null) {
//console.log(response.image);
if (response.image == null || response.image == "") {
image = "https://www.wefornews.com/wp-content/uploads/2017/01/news-3.jpg"
} else {
image = response.image;
}
}
});
callback(null, image); // Otherwise proceed as usual.
};
var updateDatabase = function(err, data) {
//if (err) throw err; // Check for the error and throw if it exists.
refupdate.update ({
"Article_Image_URL": data
});
console.log('success'); // Otherwise proceed as usual
};
getUrl(getImage);
getImage(updateDatabase);
但是我callback is not a function
在线路上遇到错误callback(null, image);
问题是,如果我删除该updateDatabase
功能,则不会出现任何错误。但是,当它在代码中时,我会收到上面提到的错误。有人可以告诉我是什么导致了这个错误?
调用时getUrl(getImage)
,该getImage
函数将作为callback
参数传递给getUrl
。getUrl
然后调用这个callback
参数,传递两个参数。
callback(null, article_url)
但getImage
需要三个参数
var getImage = function(err, data, callback)
所以函数callback
内部getImage
是未定义的,当你尝试调用 undefined 作为函数时
callback(null, image)
...你得到你的callback is not a function
错误。
解决方案
您需要嵌套回调,以便以正确的顺序调用函数,并使用正确的参数。
getUrl(function (err, article_url) {
getImage(err, article_url, function (err, image) {
updateDatabase(err, image);
});
});
这也可以简化,因为您想updateDatabase
在getImage
完成后直接调用。
getUrl(function (err, article_url) {
getImage(err, article_url, updateDatabase);
});
此外,在您的 getImage 函数中,callback
会在您的textapi.extract
函数完成之前调用,这可能不是您想要的。
前
var getImage = function(err, data, callback) {
textapi.extract({
url: data,
best_image: true
}, function(error, response) {
/* code */
});
callback(null, image); // This will get called immediately, without waiting for textapi.extract
};
后
var getImage = function(err, data, callback) {
textapi.extract({
url: data,
best_image: true
}, function(error, response) {
/* code */
callback(null, image); // Callback moved here, so it gets called after textapi.extract completes
});
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句