javascript - 如何使单独的同步功能等待另一个异步功能?
问题描述
我无法在另一个异步函数中回调异步函数。我在控制台中收到了这个:
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 正在返回天气对象,因为我可以在返回之前对其进行控制台记录,并且可以在 callForecasrAPI 中的获取之前将其返回。提前感谢您的任何建议。
解决方案
如果您尝试调用callWeatherAPI()
并将其实际结果传递给另一个函数,那么您必须这样await
做。它是一个async
函数,所有async
函数都返回一个承诺。函数内部的返回值async
成为 promise 的解析值。因此,要从 Promise 中获取值,您可以使用await
or .then()
。
callForecastAPI(await callWeatherAPI(processSearchInput(searchInput)));
当然,这意味着此代码本身需要位于async
函数内部,以便您可以使用await
.
有关async
函数如何始终返回 Promise 的更多信息,请参阅为什么我需要等待异步函数,而它不应该返回 Promise?.
而且,callForecastAPI()
is 也async
返回一个 promise,因此要获得实际的 Forecast 结果,您也需要使用await
or .then()
。
const forecast = await callForecastAPI(await callWeatherAPI(processSearchInput(searchInput)));
或者,也许使用中间变量会更清楚:
const weather = await callWeatherAPI(processSearchInput(searchInput));
const forecast = await callForecastAPI(weather);
console.log(forecast);
推荐阅读
- java - Java -Spring Boot - OAuth 2.0 配置实现谷歌账号登录
- vue.js - Prop not Reactive 使用 VUE 发送配置
- spring - Spring CachingConnectionFactory 在 Tibco EMS 代理重新启动时挂起
- java - 将 JAVA_HOME 添加到 Linux - 正确方法
- windows - pyinstaller 在编译 pandas 时出现奇怪的错误
- hive - 在指定数据库之前,已应用 Sentry 授权,但 ACL 不工作
- java - 在动态代理的动态生成字节码中究竟发生了什么?
- java - Jackson JsonUnwrapped 和通用
- android - 异常逃脱了 try 块
- c# - 输入多个 id 的 GET 操作 .NET