javascript - 强制代码暂停执行,直到带有承诺的函数结束执行 - 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
}
解决方案
该函数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
})
}
推荐阅读
- amazon-s3 - 使用 boto3 键错误从 S3 下载文件
- asp.net-core - .netcore web API Post 在没有 SSL 的情况下无法工作
- c# - RestSharp 请求中的错误?, XML , ':' 字符,十六进制值 0x3A,不能包含在名称中
- java - Spring @ConfigurationProperties 解析器忽略外部化属性
- arrays - 在一行中使用 /bin/sh 声明一个数组
- java - 将 JBOSS EAP 7.1.5 迁移到 JBOSS EAP 7.2 时出现休眠问题
- node.js - 将下一个 js 更新到 v9 后链接错误 - 参数 'url' 必须是字符串,而不是未定义
- java - 如何使用java更改设备屏幕分辨率?
- angular - 除非我单击刷新,否则角度旋转木马不起作用
- java - 安装的 APK 文件未出现在主页启动器中