Is there a way to wait until a function is finished?

前端 未结 3 588
时光取名叫无心
时光取名叫无心 2021-01-24 23:20

I\'m trying to get information (true/false) from AsyncStorage in a function and create a string which is importent to fetch data in the next step. My problem is, the function is

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 00:19

    what if you wrap the _getFetchData() in a Promise? This would enable you to use

    var channel = this._getFetchData().then(console.log("channel required: " + channel));
    

    Otherwise the console.log won't wait for the execution of the _getFetchData(). This is what the console.log is telling you. it just logs the string. the variable is added after the async operation is done.

    UPDATE

    I would try this:

    //_getFetchData()
    AsyncStorage.getAllKeys().then((result) => { //get all stored Keys
      valuelength = result.length;
      if (valuelength !== 0) {
        for (let i = 0; i < valuelength; i++) {
          if (result[i].includes("not") == false) { //get Keys without not
            AsyncStorage.getItem(result[i]).then((resultvalue) => {
              if (resultvalue === 'true') {
                if (this.state.firstValue) {
                  this.state.channels = this.state.channels + "channel_id" + result[i];
                  console.log("channel: " + this.state.channels);
                }
                else {
                  this.state.channels = this.state.channels + "channel" + result[i];
                }
              }
            });
          }
    return new Promise((resolve, reject) => {
        this.state.channels !=== undefined ? resolve(this.state.channels) : reject(Error('error '));
    }
    
    _fetchData() {
    var channel = this._getFetchData().then(console.log("channel required: " + channel));
    }
    

    maybe you must change the this.state.channels !=== undefined to an expression that's matches the default value of this.state.channels.

提交回复
热议问题