我无法在另一个异步函数内部回调异步函数。 我在控制台收到这个:
Promise {<pending>}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
script.js:127 TypeError: Cannot read property 'aWeatherObjProperty' of undefined
at callForecastAPI (script.js:121)
at HTMLInputElement.<anonymous> (script.js:138)
这是我的 JavaScript 代码:
function processSearchInput(searchInput) {
// does some math. No waiting required.
return processedSearchInput;
}
// processedSearchInput is an object
// Take processedSearchInput and call OpenWeather API
async function callWeatherAPI(processedSearchInput) {
const response = await fetch(`calling API`, { mode: 'cors' });
const weather = await response.json();
return weather;
}
// weather is an object
// Call OpenWeather Forecast API and return weatherForecast object
async function callForecastAPI(weatherObj) {
const response = await fetch(`calling API`);
const weatherForecast = await response.json();
return weatherForecast;
}
callForecastAPI(callWeatherAPI(processSearchInput(searchInput)));
我确定 callWeatherAPI 正在返回天气对象,因为我可以在返回之前对它进行控制台.log,并且可以在 callForecasrAPI 中的提取之前返回它。 预先感谢您的任何建议。
答案 0 :(得分:1)
如果您尝试调用 callWeatherAPI()
并将其实际结果传递给另一个函数,那么您必须await
它。它是一个 async
函数,所有 async
函数都返回一个 promise。 async
函数内的返回值成为承诺的已解析值。因此,要从 promise 中获取值,您可以使用 await
或 .then()
。
callForecastAPI(await callWeatherAPI(processSearchInput(searchInput)));
这当然意味着此代码本身需要位于 async
函数内,以便您可以使用 await
。
有关 async
函数如何始终返回承诺的更多信息,请参阅 Why do I need to await an async function when it is not supposedly returning a Promise?。
而且,callForecastAPI()
也是 async
并且还返回一个 promise,因此要获得实际的 Forecast 结果,您还需要在其上使用 await
或 .then()
。
const forecast = await callForecastAPI(await callWeatherAPI(processSearchInput(searchInput)));
或者,使用中间变量可能更清楚:
const weather = await callWeatherAPI(processSearchInput(searchInput));
const forecast = await callForecastAPI(weather);
console.log(forecast);