【问题标题】:How i can await the result of the AsyncStorage?我如何等待 AsyncStorage 的结果?
【发布时间】:2020-08-21 15:24:09
【问题描述】:

我需要在运行其他函数之前先运行 AsyncStorage,但是 AsyncStorage 需要一些时间才能运行,它会在代码末尾给出结果

 constructor(props) {
   super(props);
  
  AsyncStorage.getItem(TOKEN).then((r) => {
    console.log("AsyncStorage Function")
  })

  this.state = { token: null } 
  console.log("The last Function")

}

【问题讨论】:

    标签: reactjs react-native


    【解决方案1】:

    假设这是一个反应类组件,理想情况下你不应该在构造函数中执行任何异步任务。

    因此,如果您希望执行任何异步任务,您可以使用组件生命周期方法中的componentDidMount

    但一般来说,如果你想等待异步操作,那么这可以通过不同的方式实现

    使用承诺

    const promiseFun = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("Success")
        }, 1000)
      })
    }
    
    promiseFun().then((res) => {
      //here res will be what is returned from the promise function
      console.log(res);
    
      //All the required things that needed to be perfomed after the async operation should be placed here.
    });
    
    
    //Whatever the actions/statements written here will be executed before the async operation is finished
    console.log("Before Promise Returned");

    使用异步/等待

    const promiseFun = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("Success")
        }, 1000)
      })
    }
    
    const execFun = async() => {
      let res = await promiseFun();
      //All the statments from here will be executed only after the promise/async function returned. 
      console.log(res);
      
    }
    
    execFun();
    //All the statements here will be executed without waiting for the promise/async function gets executed 
    console.log("Before Promise Returned");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 1970-01-01
      • 2018-08-17
      • 2020-10-31
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多