【发布时间】:2021-01-09 04:59:48
【问题描述】:
我正在尝试使用函数来保持我的代码干净。
我想创建一个可重复使用的函数 - 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
}
【问题讨论】:
-
getNumberOfCountriesDownloaded不会返回任何内容供您等待。 -
它返回国家下载的变量.....
-
不,您将其返回给 .then 回调(这是必要的,但您需要的还不止这些。)
-
同意,您应该返回
Promise本身,例如return Promise.allSettled(...) -
代码应该怎么写才能返回countryDownloaded变量?
标签: javascript function asynchronous promise async-await