【问题标题】:correct output of async await promise?异步等待承诺的正确输出?
【发布时间】:2020-06-07 17:47:30
【问题描述】:

我正在使用 firstore,我从 firstore 获取信息。

这里,我想从firstore中取数据并打印出来,但是异步模式有问题。

undefined后输出。

我想知道如何正确打印。

接收到数据时,函数接收数据,搜索firestore后接收数据的方法。

在反应组件中

  index = (date) =>{

        let date_total = UserAction.getIndex(date)

       return date_total
    }

render(){
 const {user_list} = this.props;
        console.log(this.state)
        const date = "2020-02-24"
        console.log("data",date)
        let index = this.index(date) < this
        console.log("index", index)

return(...)

和用户操作函数


export function getIndex(data){
    let time_now = moment(data).utc().format()
    const user_history_start = moment(time_now).startOf("d").utc().format();
    const user_history_end = moment(time_now).endOf("d").utc().format();
    let db = loadFB().firestore();
    let query = db.collection('users').where('create_date','>=',user_history_start).where('create_date','<=',user_history_end);
    let number ;
    return query.get().then( docs=>{

        number = docs.size
        return number
    })



 }

我想要输出

data 2020-02-24
index 11 < (firestore given data)

但输出

data 2020-02-24
index promise{<pending>} < (firestore given data)

给我一​​个好的解决方案。

【问题讨论】:

    标签: javascript google-cloud-firestore


    【解决方案1】:

    我猜你不能在渲染中打印承诺的值,而是设置状态并打印它?

    constructor() {
      super();
    
      this.state = {
        index: null
      }
    }
    
    getIndex = (date) => {
      // --------- update ----------
      UserAction.getIndex(date).then(date_total => this.setState({ index: date_total }))
    }
    
    componentDidMount() {
      const date = "2020-02-24"
      // --------- update ----------
      this.getIndex(date)
    }
    
    render() {
      console.log("index", this.state.index)
      // will first print null, 
      // then print the index when the promise is done (re-rendered due to state change)
    }
    

    您可能希望阅读this 作为参考。

    【讨论】:

    • 我尝试了我建议的两种方法,但我想要的输出不可用,等待输出。
    • @이창훈 有帮助吗?
    猜你喜欢
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 2018-03-05
    • 1970-01-01
    • 2020-03-26
    • 2018-12-24
    相关资源
    最近更新 更多