首页 > 解决方案 > 从 fetch 之外的其他地方调用在 fetch 中定义的函数

问题描述

我目前在弄清楚如何调用在 API Fetch 响应函数中定义的函数时遇到问题。我目前有一个 API 提取到 github API 以获取存储库树。它以 JSON 文件的形式返回,我的代码完成了所有工作。问题是我有一个在 fetch 中定义的函数(我想在 fetch 之外调用,所以我不必每次都“重新获取”),我不能在 fetch 之外调用它(它有点像函数内部的函数)。

我在网上四处寻找并四处询问,我似乎找不到任何答案。我对 JS 很陌生(是的,我知道我的代码很乱)。

这是我当前代码的片段:

fetch(api_TreeURL)
    .then(function(response) {
        return response.json()
    }).then(function(json) {
        function GetSortOrder(prop) {    
            return function(a, b) {    
                if (a[prop] > b[prop]) {    
                    return 1;    
                } else if (a[prop] < b[prop]) {    
                    return -1;    
                }    
                return 0;    
            }    
        }    

        function DELTA_location(currrentlLocation) {
            var parentlocation = document.getElementById("delta");
            var dirLocation = document.createElement("div")
            var dirLocationText = document.createElementNS("http://www.w3.org/1999/xhtml","a")
            var lastChar = currrentlLocation.substr(-1);
            
            parentlocation.append(dirLocation)
            dirLocation.append(dirLocationText)
            dirLocation.setAttribute("class","delta-location")
        
            if (lastChar != '/') {
                currrentlLocation = currrentlLocation + '/';
            }
        
            dirLocationText.innerHTML = currrentlLocation
        }
    }).catch(function(ex) {
        console.log('parsing failed', ex)
})

如果我尝试DELTA_location("")从 fetch 之外的任何地方打电话,例如;

fetch(api_TreeURL)
    "...the code..."
})

DELTA_location("test")

它将返回错误:Uncaught ReferenceError: DELTA_fetch is not defined 如果我从 HTML 文件中的按钮调用它,则相同。

如果您想查看所有代码,请访问Github

标签: javascriptfunctionfetch

解决方案


您可以做的是使用对该函数的引用,例如:在您编写的获取代码之外

let DELTA_location_ref = (a) => console.warn('Function not fetched yet');

然后在获取代码中,您将此变量覆盖为:

DELTA_location_ref = (currrentlLocation) =>  {
        var parentlocation = document.getElementById("delta");
        var dirLocation = document.createElement("div")
        var dirLocationText = document.createElementNS("http://www.w3.org/1999/xhtml","a")
        var lastChar = currrentlLocation.substr(-1);
        
        parentlocation.append(dirLocation)
        dirLocation.append(dirLocationText)
        dirLocation.setAttribute("class","delta-location")
    
        if (lastChar != '/') {
            currrentlLocation = currrentlLocation + '/';
        }
    
        dirLocationText.innerHTML = currrentlLocation
    }

在这里使用闭包(箭头函数)很重要,因为您希望在从外部调用时访问 fetch 的上下文

请注意,您的 delta 位置函数不使用 fetch(json 变量)的返回,所以我不知道您为什么在那里定义它


推荐阅读