带有函数返回的简单异步等待问题

我对异步函数有一个简单但令人困惑的问题。我希望在函数准备好时简单地返回值。


这是一个示例代码:


async function test() {

  setTimeout(function() {

    return 'eeeee';

  }, 5000);

}


test().then(x => {

  console.log(x)

});


小怪兽爱吃肉
浏览 74回答 3
3回答

不负相思意

您将立即获得未定义的记录。很明显,您正在尝试编写一个sleep()异步函数,但请记住 setTimeout 是一个同步函数,使用回调函数调用将在给定时间执行,因此在您执行test()时,调用将运行到结束,return undefined就像您有函数体中没有 return 语句,它将被传递给你的.then()函数。正确的方法是返回一个在给定时间后解决的 Promise,这将继续then调用。async function sleep(time){  return new Promise((resolve,reject) => {    setTimeout(() => {      resolve("echo str")    },time)  })}sleep(5000).then((echo) => console.log(echo))简而言之睡眠功能const sleep = async time => new Promise(resolve=>setTimout(resolve,time))

慕哥9229398

承诺const setTimer = (duration) => {      const promise = new Promise((resolve, reject) => {        setTimeout(() => {          resolve('Done!');        }, duration);      });      return promise;    };        setTimer(2000).then((res) => console.log(res));

繁华开满天机

异步函数必须返回一个承诺。所以要解决这个问题,你可以将你的setTimeout函数包装在一个新的 Promise 中,如下所示:async function test(){  return await new Promise((resolve, reject) => {      setTimeout(function(){          resolve('eeeee');      },5000);  })}test().then(x => {  console.log(x)});您可以在此处的 MDN 文档中了解有关 async/await 的更多信息。希望这可以帮助!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript