首页 > 解决方案 > 如何使单独的同步功能等待另一个异步功能?

问题描述

我无法在另一个异步函数中回调异步函数。我在控制台中收到了这个:

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 中的获取之前将其返回。提前感谢您的任何建议。

标签: javascriptasynchronousasync-awaitpromiseecmascript-2017

解决方案


如果您尝试调用callWeatherAPI()并将其实际结果传递给另一个函数,那么您必须这样await做。它是一个async函数,所有async函数都返回一个承诺。函数内部的返回值async成为 promise 的解析值。因此,要从 Promise 中获取值,您可以使用awaitor .then()

callForecastAPI(await callWeatherAPI(processSearchInput(searchInput)));

当然,这意味着此代码本身需要位于async函数内部,以便您可以使用await.

有关async函数如何始终返回 Promise 的更多信息,请参阅为什么我需要等待异步函数,而它不应该返回 Promise?.

而且,callForecastAPI()is 也async返回一个 promise,因此要获得实际的 Forecast 结果,您也需要使用awaitor .then()

const forecast = await callForecastAPI(await callWeatherAPI(processSearchInput(searchInput)));

或者,也许使用中间变量会更清楚:

const weather = await callWeatherAPI(processSearchInput(searchInput));
const forecast = await callForecastAPI(weather);
console.log(forecast);

推荐阅读