0

Basically I have a loop where I find an url in an api, then I need to return it and use it outside of the loop, in order to return it to the client.

but im not able to access urlFinal from outside of the loop..

this the code

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,
    }),
}
DarkBee
  • 16,592
  • 6
  • 46
  • 58

2 Answers2

0

This behavior is because the value of urlFinal may not be assigned when you want to use it since it takes time for the asynchronous part of your code to assign value to it. You can do something like this...

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
}
  • Thanks for your help. I just tried it but when I tried to return urlFinal it is undefined. I tried like this function useUrlFinalOutside(urlFinal) { // your code that uses urlFinal return { statusCode: 200, // <-- Important! body: JSON.stringify({ id: transaccion, link: urlFinal, }), } } – David Garcia Jul 30 '21 at 06:27
  • I think this might be because the value you pass as urlFinal is undefined. I added the check in the if clause too. – MediumSpringGreen Jul 30 '21 at 06:49
0

You actually don't need a setInterval.

You can use async function with await.

Set a while loop and when you get a response, you can break the while loop.

I also use a delay function to delay each API call not to utilizes the program.

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);
ikhvjs
  • 5,316
  • 2
  • 13
  • 36
  • Thanks a lot. but it still returns undefined .. the reason that I had the setInterval Loop was because in the begining the api doesnt provide the extra field, but after a few mili seconds it provides the extra field.. – David Garcia Jul 30 '21 at 07:33
  • @DavidGarcia, I updated my answer. I log the `asyncPaymentUrl ` once you receive it. Please let me know if you receive it in the console. The logic actually is check every 3 seconds if you can get a responses that contains a `async_payment_url`, if so, it will return, otherwise it will not return until it get the `async_payment_url`. – ikhvjs Jul 30 '21 at 07:48
  • TypeError: Cannot read property 'async_payment_url' of undefined -> I get this in Console. – David Garcia Jul 30 '21 at 07:55
  • @DavidGarcia, Thanks for your reply. I made a mistake. I now add optional chaining `?.` and please try again. – ikhvjs Jul 30 '21 at 08:02