【问题标题】:Force code to pause executing until a function with a promise in it has concluded executing - javascript强制代码暂停执行,直到带有承诺的函数结束执行 - javascript
【发布时间】: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


【解决方案1】:

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

   })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多