承诺返回未定义的变量

时间:2018-07-21 23:36:02

标签: node.js

是的,我尝试了其他找到的解决方案,但无济于事。我试过在promise之上设置一个变量(区域),但意识到它超出了范围,所以这是我的下一个解决方案。每当我尝试返回区域时,它都会以未定义的形式返回。每当我console.log它(在同一位置)时,它都可以正常工作。有什么见解吗?

编辑:iplocation是一个npm软件包iplocation

function getRegion(ipAddr) {
    iplocation(ipAddr)
        .then(res => {
            if (res.country == 'US') {
                region = res.country + "-" + states[res.region_code];
            } else {
                region = res.country;
            }
            return region;
        })
}

4 个答案:

答案 0 :(得分:0)

承诺异步运行。这意味着在运行.then部分时,外部函数已返回未定义状态。您可以使外部函数async,然后使await成为Promise的值。

答案 1 :(得分:0)

async function getRegion (ipAddr) {
  let res
  try {
    res = await iplocation(ipAddr)
    if (res.country === 'US') {
      return `${res.country} - ${states[res.region_code]}`
    } else {
      return res.country
    }
  } catch (err) {
    throw err
  }
}

用法:

getRegion('8.8.8.8')
  .then(loc => console.log(loc))
  .catch(err => console.log(err))

答案 2 :(得分:0)

您的操作是异步的,因此您需要返回一个Promise,并且调用方需要对其使用.then()

function getRegion(ipAddr) {
    // return the promise
    return iplocation(ipAddr).then(res => {
        // return value will be resolved value of the promise
        if (res.country == 'US') {
            return res.country + "-" + states[res.region_code];
        } else {
            return res.country;
        }
    });
}

getRegion(...).then(region => {
  // use the region in here
  console.log(region);
}).catch(err => {
  // handle error here
  console.log(err):
});

答案 3 :(得分:-1)

您需要返回您正在等待的承诺。您可以使用return new Promise(...)或使用async/await,如下所示。

async function getRegion(ipAddr) {
   const res = await iplocation(ipAddr)
   if (res.country == 'US') {
     return res.country + "-" + states[res.region_code];
   }
   return res.country;
}
相关问题