简体   繁体   English

异步等待承诺的正确输出?

[英]correct output of async await promise?

I'm using the firstore, and I get information from the first.我正在使用 firstore,我从第一个那里获取信息。

Here, I want to retrieve data from the firstore and print it out, but there is a problem with asynchronous mode.在这里,我想从firstore中检索数据并打印出来,但是异步模式有问题。

The output is output after undefined.输出未定义后的输出。

I want to know how to print it correctly.我想知道如何正确打印。

When data is received, the function receives data, and the method of receiving data after searching the firestore.接收数据时,函数接收数据,以及搜索firestore后接收数据的方法。

in react component在反应组件中

  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(...)

and useraction function和用户操作功能


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
    })



 }

i want output我想要输出

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

but output但输出

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

Give me a good solution.给我一个好的解决方案。

I guess you can't print a promised value in render, set the state and print it instead?我猜你不能在渲染中打印承诺的值,设置状态并打印它?

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)
}

You may want to read this as a reference.您可能希望阅读本文作为参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM