简体   繁体   English

返回在匿名函数中不起作用

[英]Return not working inside anonymous function

function mapHasStops(callback) {
    app.map.mapObject.getVisibleRegion(function (bounds) {
        for (var i = 0; i < app.map.mapContent.length; i++) {
            (function (i) {
                app.map.mapContent[i].getPosition(function (position) {
                    if (bounds.contains(position)) {
                        callback(true);
                        return;
                    }
                });
            })(i);
        }
    });
}

function updateScreenContent() {
    mapHasStops(function (bool) {
        alert(bool);
    });
}

Despite returning immediately after a successful match, the alert is called multiple times (depending on how many matches it finds) when the updateScreenContents function is only called once. 尽管成功匹配后会立即返回,但是当updateScreenContents函数仅被调用一次时, alert会被多次调用(取决于找到的匹配项数)。 Any ideas why? 有什么想法吗?

Just fixing the code would be: 只需修复代码将是:

function mapHasStops(callback) {
    app.map.mapObject.getVisibleRegion(function (bounds) {
        var found = false;
        for (var i = 0; i < app.map.mapContent.length && !found; i++) {
            (function (i) {
                app.map.mapContent[i].getPosition(function (position) {
                    if (bounds.contains(position)) {
                        found = true;
                        callback(true);
                        return;
                    }
                });
            })(i);
        }
    });
}

function updateScreenContent() {
    mapHasStops(function (bool) {
        alert(bool);
    });
}

But there is probably a better way to write that function... 但是可能有更好的方法来编写该函数...

A return statement only exits from its own execution context, not any outer context. return语句仅从其自己的执行上下文中退出,而没有任何外部上下文。 In this case, the value is returned and used by getPosition : 在这种情况下,该值由getPosition返回并使用:

    // Enclosing context
    (function (i) {
                                          // Function expression is passed to *getPosition*
                                          // whose return value is not assigned
        app.map.mapContent[i].getPosition(function (position) {
            if (bounds.contains(position)) {
                callback(true);
                return;
            }
        });
    })(i);

So the function expression starting function (position) is passed to the getPosition method, which presumably calls it. 因此,函数表达式的起始function (position)将传递给getPosition方法,该方法大概会调用它。 It's value is returned there and proceeds to do whatever. 它的值在那里返回并继续执行任何操作。 It doesn't return any further than that. 它没有返回更多的信息了。

Does "function (position)" pass as a callback function? “函数(位置)”是否作为回调函数传递? If yes the for loop won't wait for it to return thus "function (position)" was called multiple times. 如果是,则for循环将不等待其返回,因此多次调用了“函数(位置)”。

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

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