繁体   English   中英

我如何等待 AsyncStorage 的结果?

[英]How i can await the result of the AsyncStorage?

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

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

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

}

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

因此,如果您希望执行任何异步任务,您可以使用组件生命周期方法中的 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");

暂无
暂无

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

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