Search code examples
javascriptes6-promise

React Native I can't get a result with a promise


Apparently simple: wait to get a result to set a state with a promise

button:

onPress: () => sessionEnded(),

function:

 const sessionEnded = async () => {
    const getTime = await totalTime(); // execution of the function bellow
    console.log('getTime', getTime);// I get undefined
    try {
      SoundPlayer.playSoundFile('end_bell', 'mp3');
    } catch (error) {
      console.log(error);
    }

    props.navigation.navigate('Daily', {time: time});
  };

function to calculate time:

  const totalTime = () => {
    let res = sessionTime - time.secs;
    console.log('totaltime calculated', res);
    return new Promise(res => setTime(res));
  };

Actually I'm new here and I don't know how to use promises. Thanks!


Solution

  • Your variables are a bit mixed up. You declare res in totalTime but then redeclare it in a new scope in the promise callback. This won't work. Also, Promises return two values in their callback - resolve and reject, both of which are methods themselves. So your value res in the Promise scope is actually a reference to a method. Using resolve correctly will return the value of the promise to the parent function. Also setTime is not defined - I assume it is elsewhere. Otherwise remove that too.

    So try modifying your code to:

    const sessionEnded = async() => {
      const getTime = await totalTime(); // execution of the function bellow
      console.log('getTime', getTime); // I get undefined
    };
    
    const totalTime = () => {
      let res = 10 - 5
      console.log('totaltime calculated', res)
      return new Promise(resolve => resolve(res))
    }
    
    sessionEnded()

    When sessionEnded is called it should now get the value of res.