【问题标题】:Wait until all the callbacks have been called等到所有回调都被调用
【发布时间】:2019-02-22 21:09:21
【问题描述】:

我在 react native 中有一个组件,可以显示用户的所有聊天记录。主要逻辑必须在 componentDidMount() 中。这里是简化版:

componentDidMount(){
     ConnectyCube.chat.list({}, function(error, dialogs) {
        chats = dialogs.map(chat => {
            const opponentId = //some logic
            ConnectyCube.users.get(function(error, res){
                //some logic to populate chats 
            });
            }
        )

        this.setState({chats: chats})
        }
    );
}

换句话说,主要问题是我不知道如何使用多个回调(用户拥有的每个聊天一个)来处理数据结构“聊天”,以便在最后设置状态。 也许,我的问题是我正在以同步的方式思考,因为我是事件驱动方法的新手。任何帮助表示赞赏。

【问题讨论】:

  • 你可能想看看这个承诺
  • 没错,也许是Promise.all
  • “手动方式”是跟踪已完成的响应数量,当该值等于数组中的项目数时,您会触发一些“最终回调”
  • ConnectyCube 是一个不提供承诺,而只提供回调的 API。
  • @James 我如何跟踪已完成的回复数?

标签: javascript react-native callback connectycube


【解决方案1】:

这是一种跟踪剩余请求数量并在它们全部完成时触发一些代码的方法。请注意,这几乎正是 Promise.all 所做的。

//some kind of global or component level variable, tracks the number of pending requests left
var remaining = 0;

componentDidMount(){
     ConnectyCube.chat.list({}, function(error, dialogs) {
        // set remaining to how many dialogs there are
        remaining = dialogs.length;
        chats = dialogs.map(chat => {
            const opponentId = //some logic
            ConnectyCube.users.get(function(error, res){
                //some logic to populate chats

                // decrement remaining and check if we're done
                if (--remaining === 0) {
                  finalCallback(); // in here you do your setState.
                }
            });
            }
        )

        this.setState({chats: chats})
        }
    );
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-06
    • 2019-05-22
    • 2021-05-25
    • 2014-06-03
    • 2021-01-25
    • 1970-01-01
    • 2017-09-03
    • 1970-01-01
    相关资源
    最近更新 更多