简体   繁体   中英

Unexpected behavior in asynchronous JavaScript API call

I make an API call to ContractService.getAppData() . The object it returns, appDataResult will always contain a success key which will be a boolean .

The issue is that the request succeeds, but before it prints console.log('success') , it prints console.log('failure') . Meaning the request is interpreted as failed at first, which effects the related logic which is important to the app state.

const fetchAppData = async () => {
  try {
    const appDataResult = await ContractService.getAppData()
    if (appDataResult.success) {
      console.log('success')
     // Related logic
    } else {
      console.log('failure')
     // Related logic
    }
  } catch (e) {
    console.error(e)
  }
}

The fetchAppData function is called from a useEffect like so:

 useEffect(() => {
  if(isLoggedIn && isSelectedAsset) {
    fetchAppData()
  }
 }, [isLoggedIn, isSelectedAsset])

What am I missing?

The only way it can print failure , then success , is if your function is being called twice. You need to check where fetchAppData() is being called.

Also, to get another obvious failure out of the way - is there another console.log('failure') anywhere?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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