j.doe
j.doe

Reputation: 4859

Call an asynchronous function with react

I write this function in a static class

  remove(){
    Keychain
    .resetGenericPassword(Config.keychainGroupe)
    .then(function() {
      AsyncStorage.removeItem('data', (err) => console.log('data deleted, return true', err));
    });
  }

I want to asynchronously return true if the data are successfully deleted so I would be able to use the function by calling await MyClass.remove(). I tried to return true after removing the item from the AsyncStorage but I am getting undefined when I call the function with awairt

Upvotes: 2

Views: 123

Answers (3)

Shubham Khatri
Shubham Khatri

Reputation: 281656

You can make use of async-await

 async remove(){
        try {
          const data = await Keychain.resetGenericPassword(Config.keychainGroupe)
          try {
            await AsyncStorage.removeItem('data');
            return true;
          } catch (error) {
              return false
          }
        }
        catch(error) {
             console.log('keychain method failed')
        }
    }

Upvotes: 0

You can use either Promise or async-await.

The exact way to return the value from then method of a promise is as follows

1) Using Promises

remove(){

    //Notice return before the Keychain

    return Keychain
        .resetGenericPassword(Config.keychainGroupe)
        .then(function() {
            AsyncStorage.removeItem('data', (err) => console.log('data deleted, return true', err));
            return true;
        });
}

or

remove(){
    return new Promise((resolve, reject) => {
        Keychain
            .resetGenericPassword(Config.keychainGroupe)
            .then(() => {
                AsyncStorage.removeItem('data', (err) => console.log('data deleted, return true', err));
                resolve(true);
            }).catch((err) => {
            reject(err);
        });
    });
}

2) Using async-await

    async remove(){
            try {
              const resolvedData= await Keychain.resetGenericPassword(Config.keychainGroupe)
              if(resolvedData){
                  try {
                      await AsyncStorage.removeItem('data');
                      return true;
                  } catch (err) {
                      console.log('data deleted, return true', err);
                  }
              }
            }
            catch(err) {
                 console.log('Something went wrong with executing resetGenericPassword');
            }
        }

Upvotes: 1

FredG
FredG

Reputation: 276

Try return Promise.resolve(true);. It will wrap the true value in a Promise at the next event loop type. For more details about promises, check the mdn promises documentation and/or the Promises chapter from the great book series You don't know JS

Upvotes: 0

Related Questions