基本上我有一个循环,我在一个 api 中找到一个 url,然后我需要返回它并在循环之外使用它,以便将它返回给客户端。
但我无法从循环外部访问 urlFinal..
这是代码
let urlFinal
const bucle = setInterval(function () {
console.log('antes de Axios')
axios
.get(url, {
headers: { Authorization: AuthorizationWompi },
})
.then(function (response) {
console.log('Then antes de If')
if (response.data.data.payment_method.extra.async_payment_url) {
urlFinal =
response.data.data.payment_method.extra.async_payment_url
clearInterval(bucle)
console.log('al final del if')
}
})
}, 1000)
console.log(urlFinal)
return {
statusCode: 200, // <-- Important!
body: JSON.stringify({
id: transaccion,
link: urlFinal,
}),
}
答案 0 :(得分:0)
这种行为是因为 urlFinal
的值在您想使用它时可能没有分配,因为代码的异步部分需要时间为其分配值。你可以做这样的事情...
const bucle = setInterval(function () {
console.log('antes de Axios')
axios
.get(url, {
headers: { Authorization: AuthorizationWompi },
})
.then(function (response) {
console.log('Then antes de If')
if (response.data.data.payment_method.extra.async_payment_url && typeof response.data.data.payment_method.extra.async_payment_url !== 'undefined') {
useUrlFinalOutside(response.data.data.payment_method.extra.async_payment_url)
clearInterval(bucle)
console.log('al final del if')
}
})
}, 1000)
function useUrlFinalOutside(urlFinal){
// your code that uses urlFinal
}
答案 1 :(得分:0)
您实际上不需要 setInterval。
您可以将 async function
与 await
一起使用。
设置一个while循环,当你得到响应时,你可以打破while循环。
我还使用 delay
函数来延迟每个 API 调用以不使用该程序。
const delay = ms => new Promise((resolve, reject) => setTimeout(resolve, ms));
async function run() {
let urlFinal;
while (true) {
console.log("antes de Axios");
const response = await axios.get(url, {
headers: { Authorization: AuthorizationWompi },
});
const asyncPaymentUrl =
response?.data?.data?.payment_method?.extra?.async_payment_url;
if (asyncPaymentUrl) {
console.log({ asyncPaymentUrl });
urlFinal = asyncPaymentUrl;
break;
}
await delay(3000);
}
const obj = {
id: transaccion,
link: urlFinal,
};
return {
statusCode: 200, // <-- Important!
body: JSON.stringify(obj),
};
}
run().then(console.log).catch(console.log);