问:问题描述
使用Vue Axios库的HTTP请求
在此请求拦截器axios.interceptors.request中。用于与IOS进行通信以获得一些移动设备信息参数,然后发送请求返回配置;
但是,当与IOS异步通信时,尚未获得IOS的响应
相关代码
axios.interceptors.request.use(config => {
//Call the IOS method to fill in the common parameters
window.__nativeFn("js_getAllDeviceInfo", {
//Response results of IOS
response: r => {
config.data = Object.assign(config.data, r.data)
}
})
return config
}, error => {
return Promise.reject(error);
});
尝试1.使用计时器查看IOS是否响应(如果未实现要求,则无法在计时器中返回config。如果在计时器中调用回调函数,则不知道如何将其返回给他axios.interceptors.request .use)
axios.interceptors.request.use(config => {
//Call the IOS method to fill in the common parameters
window.a = false
window.__nativeFn("js_getAllDeviceInfo", {
//Response results of IOS
response: r => {
config.data = Object.assign(config.data, r.data)
window.a = true
}
})
var i = 0
let SI = setInterval(() => {
i++
//If the IOS side does not respond within 5 seconds, clear the timer
if(5000 <= i) {
clearInterval(SI)
}
if(window.a) {
clearInterval(SI)
return config
}
})
}, error => {
return Promise.reject(error);
});
尝试2使用@yuanxiaowa方法发起两个API请求。第二个API请求未发送。打印的配置始终是与第一个请求有关的信息
return new Promise(resolve => {
//Call the IOS method to fill in the common parameters
window.__nativeFn("js_getAllDeviceInfo", {
//Response results of IOS
response: r => {
config.data = Object.assign(config.data, r.data)
console.log(config)
resolve(config)
}
})
})
答:axios.interceptors.request.use(config => {
return new Promise(resolve => {
//Call the IOS method to fill in the common parameters
window.__nativeFn("js_getAllDeviceInfo", {
//Response results of IOS
response: r => {
config.data = Object.assign(config.data, r.data)
resolve(config)
}
})
})
}, error => {
return Promise.reject(error);
});