【问题标题】:Passing external variables into Axios.get().then() call将外部变量传递给 Axios.get().then() 调用
【发布时间】:2021-11-01 02:21:24
【问题描述】:

我想使用 Axios 调用一个端点,然后对响应数据和调用前定义的变量做一些事情。我自己创建返回承诺的函数时知道如何pass data into the callback,但由于 Axios 是外部代码,我似乎找不到任何选项在Axios docsthe config 中传递额外数据。除了将值作为数据发送到服务器并让服务器在响应中响应它或使用window 全局变量使用丑陋的解决方法之外,还有其他方法可以使这项工作吗?

const animate = true; // The variable to be passed
axios.get('/endpoint.json')
    .then(function(response, animate) { // This doesn't work...
        if (response.data.coordinates) {
            console.log(animate); // ...because this is undefined
            setLocation('takeoff_location', response.data.coordinates, animate); // variable and response data need to be passed to this call
        }
    });

【问题讨论】:

  • 为什么不直接访问aninate变量,你不需要它作为then()的参数

标签: javascript promise axios scope


【解决方案1】:

.then() 是一个承诺,可以访问范围之外的任何变量(如闭包)。如果您想封装 API 调用,则将整个内容包装在一个函数中,然后将参数放在那里。

const doRequest = function(animate) {
  axios.get('/endpoint.json').then(function(response) {
    if (response.data.coordinates) {
      setLocation('takeoff_location', response.data.coordinates, animate);
    }
  });
};

doRequest(250);
doRequest(500);

请注意,这将快速连续执行 2 个动画请求。如果您想“等待”另一个先完成,您可以这样做:(请注意,我现在从函数返回 axios 请求)。这意味着返回了 promise 对象,现在您可以在函数的“外部”链接更多 .then() 函数,这只会在请求完成时发生。

const doRequest = function(animate) {
  return axios.get('/endpoint.json').then(function(response) {
    if (response.data.coordinates) {
      setLocation('takeoff_location', response.data.coordinates, animate);
    }
  });
};

doRequest(250).then(function() {
  // this will happen when the outer API call finishes
  doRequest(500);
});

【讨论】:

    【解决方案2】:

    这会创建一个 animate 变量,与已经定义的完全无关:

    function(response, animate)
    

    这个新变量“遮蔽”了更高范围内的那个,所以在这个函数中任何对animate的引用都只引用这个新变量。未定义是因为 Axios(特别是 .get() 返回的 Promise)没有理由向此回调传递第二个值。

    不要隐藏变量:

    function(response)
    

    然后在函数内任何对animate 的引用都将引用更高范围内的变量。

    【讨论】:

    • 我首先尝试了这个,但这给了我比我设置的另一个值。现在发现我已经覆盖了介于两者之间的变量,这导致了错误。
    猜你喜欢
    • 2018-01-03
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    相关资源
    最近更新 更多