我只是在学习javascript中的回调,我想要一些关于以下代码的帮助:
(请阅读整篇文章:我意识到没有设置exists )。
window.addEventListener('load', function(){
for (let count = 1; count <= 10; count++) {
var toTest = "pic" + count + "a.jpg";
var exists;
imageExists(toTest, function(response){ if(response == true){ console.log("true" + count); exists = true; } else { console.log("false" + count ); exists = false;}});
console.log(exists);
if(!exists){break;}
}
});
function imageExists(image_url, callback){
console.log("processing: " + image_url);
var http = new XMLHttpRequest();
http.open('HEAD', image_url, true);
http.send();
http.onload = function() {
console.log(http.status);
if (http.status != 404) {
console.log(image_url + " exists (in imageExists)");
callback(true);
} else {
console.error(image_url + "does not exist (in imageExists)");
callback(false);
}
}
}当然,这不起作用,因为它在回调之前检查exists变量。我试着用break替换exists = false;,但这是非法的。
有什么解决方案可以在不完全更改代码的情况下将回调从函数中提取出来?
控制台日志为:
processing: pic1a.jpg
app.js:14 undefined
app.js:56 200
app.js:58 pic1a.jpg exists (in imageExists)
app.js:13 true1发布于 2018-03-23 10:38:52
这是一个非常常见的情况,我们应该使用promise和async/await。就重构现有代码而言,这种方法也是一种只需最小工作量的方法。您可以将imageExists()转换为返回promise对象的函数,然后它将能够用作:
result = await imageExists(imgUrl);而不是:
imageExists(imgUrl, callback(result) => {...});想要学习更多高级技能,请查看ReactiveX libray。
发布于 2018-03-23 10:35:03
一个足够简单的解决方案是将侦听器转换为异步函数,将imageExists转换为Promise,然后对其执行await操作:
window.addEventListener('load', async function() {
for (let count = 1; count <= 10; count++) {
const toTest = "pic" + count + "a.jpg";
const response = await imageExists(toTest);
const exists = response.ok;
if (!exists) {
console.log('does not exist');
break;
}
}
}
function imageExists(image_url) {
console.log("processing: " + image_url);
return fetch(image_url, { method: 'HEAD' });
}
发布于 2018-03-23 10:41:24
所以,我认为:
function imageExists(image_url, callback) {
console.log("processing: " + image_url);
var img = document.createElement("IMG");
img.load = function() { callback(true); };
img.error = function() { callback(false); };
img.src = image_url;
}https://stackoverflow.com/questions/49441442
复制相似问题