【问题标题】:I want to run a JavaScript code synchronously in react native我想在本机反应中同步运行 JavaScript 代码
【发布时间】:2022-01-11 18:40:49
【问题描述】:

我在一个项目中工作,我使用 SQLite 从本地数据库中检索数据,然后处理数据,最后在计算方法中使用处理后的数据。

问题是代码是异步运行的,所以当我第一次调用计算方法时,它在检索和处理方法之前起作用,它只在第二次或第三次运行时起作用。

我有 4 种检索方法:

    retrieve1();
    retrieve2();
    retrieve3();
    retrieve4();

然后我想处理检索到的数据所以我有以下方法:

processRetrieve1();
processRetrieve2();
processRetrieve3();
processRetrieve4();

最后我要调用计算方法:

Calculate();

如何按以下顺序运行此代码? 检索方法 -> 处理方法 -> 计算方法

【问题讨论】:

  • 如果这些方法返回承诺,为什么不尝试使用Promise.all
  • 不要尝试同步运行异步代码。一旦它是异步的,它就是异步的。您可以使用async/await 让它感觉更像是同步代码。更多细节似乎是必要的——代码是存根代码/伪代码,所以它不是很有建设性。
  • 如果你想在这个领域取得成功,你需要拥抱异步编程,而不是与之抗争。

标签: javascript reactjs react-native sqlite


【解决方案1】:

如果这些方法异步工作,那么您只需使用 await 等待它们返回其输出,然后使用 Promise.all 将 promise 分组,如下所示:

const retrievePromises = [retrieve1(), retrieve2(), retrieve3(), retrieve4()]
await Promise.all(retrievePromises) // Wait for all retrieve function to be resolved

const processPromises = [processRetrieve1(), processRetrieve2(), processRetrieve3(),processRetrieve4()]
await Promise.all(processPromises) // Wait for all processRetrieve function to be resolved

await Calculate() // Will then wait for the calculate function to resolve

为了能够使用await 关键字,您必须在async 函数的范围内,如下所示:

const asyncFunc = async () => {
  await Promise.all(...)
}

如果你想了解更多,我建议你阅读更多文档,你也可以阅读这个article

请注意,Promise.all 是异步工作的,因此 promise 的解析顺序不一定与数组中的顺序相同。如果顺序很重要,那么您必须等待每个函数,如下所示:

await retrieve1();
await retrieve2();
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-04
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多