简体   繁体   English

从javascript中的单独线程传递/访问值

[英]Passing/Accessing values from separate thread in javascript

I am trying to use following code which I had found/edited in another post. 我正在尝试使用在另一篇文章中找到/编辑的以下代码。 I would like to use the function "IsValidImageUrl()" to instantly return result on the fly. 我想使用函数“ IsValidImageUrl()”即时即时返回结果。 Since this function runs in a separate thread, I had a trouble getting the value, for example, if I had "return True;" 由于此函数在单独的线程中运行,因此在获取值时遇到了麻烦,例如,如果我具有“ return True”; in place of "isValid=true;" 代替“ isValid = true;” I always get "undefined" in return. 我总是得到“未定义”作为回报。 So I tried to use global variable "isValid", but it always seem to be one step behind, meaning I need to call the function twice, to get the result for the first call. 因此,我尝试使用全局变量“ isValid”,但它似乎总是落后一步,这意味着我需要两次调用该函数,才能获得第一次调用的结果。

What am I fundamentally missing? 我从根本上缺少什么? or would you be able to suggest another method that I can do it? 还是您可以建议我可以使用的另一种方法?

Thank you! 谢谢!

<script>
    var isValid;
    function IsValidImageUrl(url) {
        $("<img>", {
                      src: url,
                      error: function() { isValid=false; },
                      load: function() { isValid=true; }
                    });
     }

    IsValidImageUrl("https://www.google.com/logos/2012/hertz-2011-hp.gif");
    alert(isValid);
    IsValidImageUrl("http://google.com");
    alert(isValid);
</script>

The problem is you have to wait for the image to either load or fail before you can use the status. 问题是您必须等待映像加载或失败,然后才能使用状态。 The best way is to give the IsValidImgUrl function a callback function (or seperate ones for success and failure) to run when the image has loaded or an error has occured. 最好的方法是为IsValidImgUrl函数提供一个回调函数(或单独的函数,以确保成功和失败)在加载图像或发生错误时运行。
In this example the image element is also passed to the callback functions, so that they know which image they were called for. 在此示例中,还将image元素传递给回调函数,以便它们知道调用了哪个图像。

 function IsValidImageUrl(url, okFunc, errFunc) { var image = document.createElement("IMG"); image.src = url; image.onload = function() {okFunc(image)}; image.onerror = function() {errFunc(image)}; } function imageLoadSucces(image) { alert("image loaded: " + image.src); } function imageLoadFail(image) { alert("image load error: " + image.src); } IsValidImageUrl("https://www.google.com/logos/2012/hertz-2011-hp.gif", imageLoadSucces, imageLoadFail); IsValidImageUrl("http://google.com", imageLoadSucces, imageLoadFail); 

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

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