【问题标题】:fetch() request returning pending Promise, not final value [duplicate]fetch() 请求返回待处理的 Promise,而不是最终值 [重复]
【发布时间】:2020-01-21 07:43:37
【问题描述】:

恐怕我对异步性、承诺和获取请求感到困惑。

我正在尝试从 fetch 请求中获取数据,您认为这很简单,但是当我运行它时,我得到的只是“Promise {pending}”。我已经阅读了 10 多个与我非常相似的答案,但似乎没有任何效果。

当我在最后的 then() 中使用 console.log(data.formatted_address) 时,我得到的结果很好(在挂起的 Promise 之后),但是当我只是返回它时,最后只有“Promise {pending}”控制台日志。任何帮助将不胜感激!

const fetch = require('node-fetch');
const dotenv = require('dotenv');
dotenv.config();

function getCoordinates(address) {
  let searchAddress = address.split(" ").join("+");
  let url =
    "https://maps.googleapis.com/maps/api/geocode/json?address=" +
    searchAddress +
    "&key=" + process.env.GOOGLE_API;
  return fetch(url)
    .then(response => response.json())
    .then(data => data.results[0].formatted_address)
}

let a = getCoordinates("Buckingham Palace, London")

console.log(a)

编辑:

如果您想在家尝试,这里有一个更简单的版本,没有 API 调用!

function getCoordinates() {
  var promiseTest = new Promise(function(resolve, reject) {
    if (1 + 1 === 2) {
      resolve('pass')
    } else {
      reject('fail')
    }
  })
  return promiseTest.then(data => data);
}

console.log(getCoordinates())

进一步编辑:

所以我认为我认为 Promises & Asynchronicity 是错误的。我需要做一些关于那时的阅读。我将远离使用异步函数,而只是扩展我的承诺以包含回调。但是感谢大家的帮助!

【问题讨论】:

  • 试试getCoordinates("Buckingham Palace, London").then(console.log);
  • 刚刚试过...还有这个。 getCoordinates("Buckingham Palace, London").then(data => console.log(data)) 恐怕他们都给出 undefined!
  • @TimothyCole 能否分享一下用于测试代码的 api 密钥,您可以随时删除这个并生成一个新的。\
  • 如果他们给undefined,那么data.results[0].formatted_address似乎也是未定义的
  • 恐怕我宁愿不要。它肯定是有效的。当我使用 .then(data => console.log(data.results[0].formatted_address)) 我得到“威斯敏斯特,伦敦 SW1A 1AA,英国”。我猜你可以放弃任何承诺。

标签: javascript node.js asynchronous fetch es6-promise


【解决方案1】:

试试这个:

function getCoordinates(address) {
  let searchAddress = address.split(" ").join("+");
  let url =
    "https://maps.googleapis.com/maps/api/geocode/json?address=" +
    searchAddress +
    "&key=" + 'your key'
    return fetch(url);
}

getCoordinates('Buckingham Palace, London').then(res => res.json()).then(data => {
  console.log(data)
})

【讨论】:

  • 是的,这有效,但它并不能真正让我做我想做的事情,即从承诺中返回一个值。它只是将问题传递到 getCoordinates 函数之外。
  • 你可以在 then 块内进一步做你的工作吗?
  • @TimothyCole 由于 Javascript 的设计方式,您期望能够做的事情是不可能的。您需要将依赖于 data 的所有内容放在 .then() 回调中。
【解决方案2】:

如果您想像同步调用一样获取 Promise 的结果,您需要使用 async/await

简化的例子可能是这样的:

function getCoordinates() {
  var promiseTest = new Promise(function(resolve, reject) {
    if (1 + 1 === 2) {
      resolve('pass')
    } else {
      reject('fail')
    }
  })
  return promiseTest.then(data => data);
}

async function getAsyncData() {
    var data = await getCoordinates()
    console.log(data);
    return data;
}

getAsyncData()

注意:async/await 在 Internet Explorer 上不起作用

【讨论】:

    猜你喜欢
    • 2020-05-04
    • 2021-02-20
    • 2021-04-28
    • 2017-09-10
    • 2018-12-14
    • 2018-11-03
    • 2017-10-07
    • 2017-12-26
    • 1970-01-01
    相关资源
    最近更新 更多