如何向Axios.get()的then()回调中传递外部自定义变量
问题原因说明
Promise的then回调只会接收前一个Promise resolve的结果作为唯一入参,你在回调里新增的animate形参会覆盖外层同名变量,且没有实际值传入,因此输出undefined。你完全不需要通过服务端回传或者全局变量实现,以下是两种常用可行方案:
方案1:直接作用域访问(绝大多数场景适用)
JavaScript支持作用域链访问,只要animate和请求回调在同一个作用域下,直接访问外层变量即可:
const animate = true; // 同作用域下的变量 axios.get('/endpoint.json') .then(function(response) { if (response.data.coordinates) { console.log(animate); // 直接访问外层变量,输出true setLocation('takeoff_location', response.data.coordinates, animate); } });
如果用async/await写法逻辑更清晰:
const fetchLocation = async () => { const animate = true; const response = await axios.get('/endpoint.json'); if (response.data.coordinates) { setLocation('takeoff_location', response.data.coordinates, animate); } }
方案2:请求配置挂载自定义字段(适配跨作用域、循环请求场景)
如果你的回调和变量定义不在同一个作用域,或者需要在循环中发起多个对应不同自定义值的请求,可以把自定义值放在请求配置的自定义字段中,Axios不会将非原生配置字段发给服务端,且会将完整配置挂载到返回的response.config上:
const animate = true; axios.get('/endpoint.json', { // 自定义字段建议加特殊前缀,避免和Axios原生配置字段冲突 _custom: { animate: animate } }) .then(function(response) { const animate = response.config._custom.animate; if (response.data.coordinates) { console.log(animate); // 输出true setLocation('takeoff_location', response.data.coordinates, animate); } });
这种方案也可以完美规避循环发起异步请求时的闭包变量污染问题。
内容的提问来源于stack exchange,提问作者Axel Köhler
相关产品推荐
相关产品推荐

