【发布时间】: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