【发布时间】:2019-04-09 10:14:12
【问题描述】:
我在一个函数中有一条 fetch 指令,它从服务器获取 API 密钥,其他一些对象使用它来将该 API 密钥传递给需要它的任何服务。
export default async function getAPIKey(key) {
return await (await fetch('http://localhost:8000/' + key)).json();
}
在我的天气对象中:
export default {
URI: 'https://api.openweathermap.org',
getLocalWeather: async function(city=null, countryCode=null) {
try {
// fetch the API key from environment
const API_KEY = await getAPIKey('wx');
//... rest of code
代码可以正常工作,但我不明白为什么我需要 3 个等待语句。我不是只需要两个吗?我需要一个用于getAPIKey() 中的fetch()。然后.json() 返回一个promise,因为它必须等待响应主体,所以我需要一个await 来调用getLocalWeather() 中的函数。但如果我在getAPIKey() 中没有两个等待,它只会返回[object Response]?
基本上我想知道为什么以下错误:
export default async function getAPIKey(key) {
return (await fetch('http://localhost:8000/' + key)).json();
}
在我的天气对象中:
export default {
URI: 'https://api.openweathermap.org',
getLocalWeather: async function(city=null, countryCode=null) {
try {
// fetch the API key from environment
const API_KEY = await getAPIKey('wx');
//... rest of code
我算错了吗?因为我只看到两个 Promise。我知道 async/await 函数是底层的承诺,所以 getAPIKey() 是一个承诺,但那个承诺不是 .json() 承诺吗?如果是这样,为什么我调用该函数的 await 不够?
我不确定我没有理解什么。
【问题讨论】:
-
据我所知,无论您是从
async函数返回值的承诺还是值(甚至是值的承诺),await都应该给您价值。我想“为什么以下是错误的”实际上并没有错;当你运行它时会发生什么?因为它不可能产生Response对象 -Response是fetch承诺的值;如果您在其上运行json,它将给您一个json承诺,或者响应是JSON 编码的任何值;我不知道会在哪种情况下运行.json()而你最终得到Response。
标签: async-await es6-promise fetch-api