强制代码暂停执行,直到其中包含promise的函数结束执行javascript



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

我想创建一个可重复使用的函数getNumberOfCountrysDownloaded((,用于计算我下载的国家数量。

这个函数包含一个promise,并在promise执行完毕后返回一个值。

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

是否可以暂停执行,直到getNumberOfCountrysDownloaded((函数完成执行其代码?

如果没有,写干净代码和有承诺的干码的最佳方式是什么?

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
}

函数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
})
}

最新更新