首页 > 解决方案 > 强制代码暂停执行,直到带有承诺的函数结束执行 - javascript

问题描述

我正在尝试使用函数来保持我的代码干净。

我想创建一个可重用的函数——getNumberOfCountriesDownloaded()——计算我下载的国家数量。

这个函数里面有一个 Promise,当 Promise 执行完成时返回一个值。

问题是当我(从另一个函数)调用这个函数时,它会立即执行下一行......所以我保存 getNumberOfCountriesDownloaded() 结果的变量是未定义的。

是否可以暂停执行直到 getNumberOfCountriesDownloaded() 函数完成其代码的执行?

如果没有,用 Promise 编写干净代码和干代码的最佳方法是什么?

function getNumberOfCountriesDownloaded(countryCodes) {

  let CountriesDownloaded = countryCodes.map(countryCode => { return localStorage.getItem(countryCode) })

  Promise.allSettled(CountriesDownloaded).then(countries => {

     let countriesDownloaded = countries.filter(country => country.value !== null).length

     return countriesDownloaded

   })
}

async function dataForGraphs(countryData) {

let countriesDownloaded = await getNumberOfCountriesDownloaded()

console.log('countriesDownloaded - after promise', countriesDownloaded)

//run rest of code
}

标签: javascriptfunctionasynchronouspromiseasync-await

解决方案


该函数getNumberOfCountriesDownloaded本身必须是一个 Promise,以便您能够await在其他函数中生成它的结果。您可以通过返回一个Promise.

function getNumberOfCountriesDownloaded(countryCodes) {

  let CountriesDownloaded = countryCodes.map(countryCode => { return localStorage.getItem(countryCode) })

  return Promise.allSettled(CountriesDownloaded).then(countries => {

     let countriesDownloaded = countries.filter(country => country.value !== null).length

     return countriesDownloaded

   })
}

推荐阅读