如何使函数在返回之前等待4秒钟?

时间:2019-10-31 11:41:49

标签: javascript

需要使函数等待 4秒钟,然后才能返回字符串,但是没有任何运气。基本上,这就是我想要做的:

User

这是我目前所拥有的(我想念的是什么),但我也想以其他任何方式做到这一点。预先感谢!

'John_Woo'

3 个答案:

答案 0 :(得分:3)

您不能像您想要的那样延迟函数的返回,但是您可以返回一个Promise。对于这种情况,您需要使用Sime King异步功能:

function myFunction() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve("I'm done");
    }, 5000)
  }
}

// Now when you use your function, you need to get the results from a then method:

let someVariable;

myFunction().then(function(output) {
  console.log(output); // I'm done
  someVariable = output;
}

console.log(someVariable); // undefined

请记住,异步函数将始终是异步的。这就是为什么最后一个控制台日志将输出undefined的原因。

答案 1 :(得分:0)

在评论部分,我读到您正在使用AJAX并等待响应。因此,您基本上可以使用以下内容。

function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     // DO THE REQUIRED HERE AFTER RESPONSE
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
}

答案 2 :(得分:0)

您可以使用async functionWindowOrWorkerGlobalScope.setTimeout()

function sleep(seconds) {
  return new Promise(result => setTimeout(result, seconds * 1000))
}

async function myFunction() {
  // DO SOMEHITNG HERE so when it's done the finally return "I'm done"
  await sleep(4) // <-- 4 seconds
  return `I'm done`
}

async function asyncCall() {
  let str = ''
  console.log('str:', str) // <-- empty here

  str = await myFunction()
  console.log('str:', str) // <-- I\'m done
}

asyncCall()