简体   繁体   English

如何使javascript检查图像存在回调函数同步

[英]How to make javascript check image exist callback function synchronous

I have this javascript function which checks if a certain image path exists.我有这个 javascript 函数来检查某个图像路径是否存在。 currently, the function is not finishing before the rest of the code is being executed.目前,在执行其余代码之前,该函数尚未完成。 if anyone can recommend a way to make the program wait till this function is finished before continuing execution that would be amazing.如果有人可以推荐一种方法,让程序等到此功能完成后再继续执行,那就太棒了。 Thanks!谢谢!

var flag = false;

function checkImageExists(imageUrl, callBack) {
    var imageData = new Image();
    imageData.onload = function () {
        callBack(true);
    };
    imageData.onerror = function () {
        callBack(false);
    };
    imageData.src = imageUrl;
}

checkImageExists(card.logoSrc, function (existsImage) {
    if (existsImage === true) {
        flag = true;
        console.log(card.logoSrc + ' ' + flag);
    } else {
        flag = false;
        console.log(card.logoSrc + ' ' + flag);
    }
});
console.log('flag ' + flag);

The console log of this program displays the image url and the correct flag value but this is only displayed after the 'flag' + flag log is executed as false at all times due to the function not finishing its execution.该程序的控制台日志显示图像 url 和正确的标志值,但这仅在 'flag' + 标志日志始终执行为 false 后显示,因为该函数未完成其执行。 Any advice or recommendations would be greatly appreciated thanks again!任何意见或建议将不胜感激再次感谢!

You could use async/await to make it act as if it was synchronous.您可以使用async/await使其表现为同步。

function checkImageExists(imageUrl) {
  return new Promise((resolve, reject) => {
    let imageData = new Image();

    imageData.onload = function () {
        resolve(true);
    };
    imageData.onerror = function () {
        reject(false);
    };

    // not really sure why you have this here, but ok
    imageData.src = imageUrl;
  });
}

async function init() {
  try {
    const isImageLoaded = await checkImageExists(card.logoSrc);
    console.log(isImageLoaded);
  } catch(error) {
    console.error(error);
  }
}

init();

Note that this is untested code, it's just to provide an idea of a solution.请注意,这是未经测试的代码,只是为了提供解决方案的想法。

Example: https://repl.it/repls/KhakiTreasuredTasks示例: https : //repl.it/repls/KhakiTreasuredTasks

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM