-
不负相思意
您将立即获得未定义的记录。很明显,您正在尝试编写一个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 的更多信息。希望这可以帮助!