node.js - Promise 返回 undefined variable

标签 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;
        })
}

最佳答案

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))

关于node.js - Promise 返回 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51460894/

相关文章:

node.js - 如何在 `npm outdated` 中包含 Beta 版本?

arrays - 将文档推送到 Mongoose 模型数组中的子文档中

node.js - 如何获取特定人员发送的电子邮件列表?

node.js - Node js 邮件喷射方法链接 stub

node.js - require ('jquery' ) vs require ('semantic-ui-css' ),只有一个可以使用 webpack 进行 React 编程

javascript - Amazon DynamoDB 的排序、跳过和限制(跳过)查询

node.js - Node js 's Buffer.toString( ' 二进制')

node.js - 为什么当我cat `/usr/local/bin`中的 Node 目录时它会释放cthulhu?

node.js - 测试方法调用

javascript - 在 express 中访问 Controller 的查询结果