0

I want to wait 3 second to return my value, but after I ran the function what I got was

result

then wait 3 seconds

function testFn() {
  setTimeout(() => console.log('wait 3 seconds'), 3000);
  return 'result';
}

testFn();

I want to wait 5 seconds to send the request if I got 'PEDING' from my first response,

so I wrote a recursion function to do it, but it doesn't work

it never wait 5 seconds then send the request.

  axios.post("api/A", searchInfo)
        .then(response => {
          if(response.data.message==='PENDING .'){
            const body={
            }

            setInterval(() => {
              console.log('wait 5 seconds first time')
          }, 5000);
          return APOSTRequest(body,dispatch,5000);

          }
    
        })
        .catch(err => {
          console.log("err", err);

        });


const APOSTRequest=(body,dispatch)=>{

  axios.post("api/A", body)
  .then(response => {
    if(response.data.message==="PENDIG."){
      setInterval(() => {
        console.log('wait 5 seconds 2nd')
    }, 5000);
     return  setTimeout(APOSTRequest(body,dispatch), 5000);
    }else{
    }
  })
  .catch(err => {
    console.log("err", err);
  });

}```
Allyssa
  • 53
  • 1
  • 9
  • 1
    There's two problems here. The short answer is: you need to move `return "result"` into the function you pass to the `setTimeout` call. The long answer is that you still cannot return a value from there though, since even if you have `const res = testFn();`, you are now returning the value inside the callback, and no longer inside `testFn`. To solve this problem, JS got Promises and async await. –  Jan 15 '21 at 09:45
  • function testFn(cb) { setTimeout(() => { cb(); }, 3000); } testFn(function(){ console.log("your result after 3 sec"); }); – Akshay Kumar Jan 15 '21 at 09:55

2 Answers2

2

For this your testFn should return a Promise which resolves after an amount of time.

function testFn(){
  return new Promise(resolve => setTimeout(() => resolve("result"),3000));
}

testFn().then(res => console.log(res));

You can do something similar with async/await too

function testFn(){
  return new Promise(resolve => setTimeout(() => resolve("result"),3000));
}

async function doIt(){
  var res = await testFn();
  console.log(res);
}

doIt()
Jamiec
  • 133,658
  • 13
  • 134
  • 193
1

In terms of async tasks, There are 3 ways to complete them:

  1. Using a callback function.

function testFn(callbackFunc) {
  setTimeout(() => {
      console.log('wait 3 seconds');
      callbackFunc(); // Invoke the callback function here.
    }, 3000);
}

testFn(function(){
  console.log("Result");
});
  1. Using Promise.

Your function should return Promise then you can resolve the value from that.

function testFn(expectedValue) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('wait 3 seconds');
      resolve(expectedValue);
    }, 3000);
  })
}

testFn(900).then(data => console.log(data));
  1. Using async/await

function testFn(expectedValue) {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('wait 3 seconds');
      resolve(expectedValue);
    }, 3000);
  })
}

async function run(){
  var data = await testFn(900);
  console.log(data)
} 

run()
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56