【问题标题】:function not being called in the then section of Promise all在 Promise all 的 then 部分中没有调用函数
【发布时间】:2020-07-14 12:49:02
【问题描述】:

在我的 componentdidmount 反应原生组件的函数中是这段代码

await Promise.all([
        this.fetchDataFromExchange(timeframes[1],false),
        this.fetchDataFromExchange(timeframes[2],false),
        this.fetchDataFromExchange(timeframes[3],false),
        this.fetchDataFromExchange(timeframes[4],false)
    ]).then(() => {this.createConfluenceSummaryTable()})

如果最后一行代码是这样的

]).then(console.log("ALL DONE"))

然后我在一切完成后在控制台中看到消息,这是正确的行为。所以我知道所有部分的承诺。 但是当我尝试调用createConfluenceSummaryTable 函数时不起作用。这个函数是同一个组件的一部分,所以我通常会使用this. 调用它。在该函数内部是另一个console.log 语句,上面写着im running,但它从不显示,这让我相信它永远不会被调用。

为什么没有调用函数?如何正确称呼它?

我试过了

]).then(result => {createConfluenceSummaryTable})

]).then(result => {this.createConfluenceSummaryTable()})

]).then(this.createConfluenceSummaryTable())

]).then(createConfluenceSummaryTable())

但似乎没有什么触发它

【问题讨论】:

  • 仅供参考,这个]).then(console.log("ALL DONE")) 不正确。应该是]).then(() => console.log("ALL DONE"))。您必须将函数引用传递给.then()。您的代码立即执行console.log(),然后什么都不传递给.then()。这可能就是您看到它执行的原因。建议您添加.catch() 以查看是否发生错误。
  • 要使用then,不要使用async/await

标签: javascript react-native promise


【解决方案1】:

您不应该需要 .then 调用,因为您使用的是 async/await:

try {
    await Promise.all([
        this.fetchDataFromExchange(timeframes[1],false),
        this.fetchDataFromExchange(timeframes[2],false),
        this.fetchDataFromExchange(timeframes[3],false),
        this.fetchDataFromExchange(timeframes[4],false)
    ]);
    this.createConfluenceSummaryTable()
} catch (e) {
    // something failed, check `e`
}

您的 .then(console.log()) 也不正确 - 您需要在 .then 中传递一个函数,而不是直接在那里调用它:() => console.log(...)

您的一个承诺很可能有一个错误,您可以使用 try/catch 捕获该错误。

【讨论】:

    猜你喜欢
    • 2015-11-08
    • 1970-01-01
    • 2020-10-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2020-06-02
    • 1970-01-01
    • 2016-12-11
    相关资源
    最近更新 更多