【问题标题】:how to access and return a variable value from outside a function [duplicate]如何从函数外部访问和返回变量值[重复]
【发布时间】:2021-07-30 05:49:41
【问题描述】:

基本上我有一个循环,我在 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,
    }),
}

【问题讨论】:

  • 循环在哪里,函数在哪里?
  • 循环是setinterval,函数只是匿名函数。整个事情都在一个开关的盒子里。

标签: javascript loops asynchronous promise


【解决方案1】:

这种行为是因为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
}

【讨论】:

  • 感谢您的帮助。我刚刚尝试过,但是当我尝试返回 urlFinal 时,它是未定义的。我试过这样的函数 useUrlFinalOutside(urlFinal) { // 你的代码使用 urlFinal return { statusCode: 200, //
  • 我认为这可能是因为您作为 urlFinal 传递的值未定义。我也在 if 子句中添加了检查。
【解决方案2】:

您实际上不需要 setInterval。

您可以将async functionawait 一起使用。

设置一个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);

【讨论】:

  • 非常感谢。但它仍然返回 undefined .. 我有 setInterval 循环的原因是因为在开始时 api 没有提供额外的字段,但在几毫秒后它提供了额外的字段..
  • @DavidGarcia,我更新了我的答案。一旦你收到它,我就会记录asyncPaymentUrl 。如果您在控制台中收到它,请告诉我。逻辑实际上是每 3 秒检查一次是否可以收到包含 async_payment_url 的响应,如果是,则返回,否则在获得 async_payment_url 之前不会返回。
  • TypeError: Cannot read property 'async_payment_url' of undefined -> 我在控制台中得到了这个。
  • @DavidGarcia,感谢您的回复。我犯了一个错误。我现在添加可选链接?.,请重试。
猜你喜欢
  • 2017-07-14
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
  • 2017-05-25
  • 2015-08-11
  • 2011-04-15
  • 2020-03-05
  • 2020-10-30
相关资源
最近更新 更多