Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native async/wait not waiting [duplicate]

I am new to react-native. I am trying to use async/await but it doesn't wait for other function to return response and alert immediately it will not wait 4 seconds. Here is my code Please help me. Thanks in advance:

import {
  AsyncStorage,
  Platform
} from 'react-native';


export const  hello =async()=>{
 const value=await refreshToken();
 alert(value);
 return "adasd";
}


const refreshToken=async()=>{
  setTimeout(async()=>{
    return true;
  },4000);
}
like image 211
Mohit Kumar Avatar asked Mar 08 '23 16:03

Mohit Kumar


1 Answers

An await can only be done on a Promise, and since setTimeout doesn't return a Promise you cannot await it. To do the same thing you are trying now, you would have to explicitly use a Promise like so:

export const  hello =async()=>{
    const value = await refreshToken();
    alert(value);
    return "adasd";
}

const refreshToken= () => {
    return new Promise(res => setTimeout(res, 4000));
}
like image 87
Moti Azu Avatar answered Mar 27 '23 06:03

Moti Azu