3 回答

TA贡献1777条经验 获得超10个赞
您将立即获得未定义的记录。
很明显,您正在尝试编写一个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))

TA贡献1877条经验 获得超6个赞
承诺
const setTimer = (duration) => {
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Done!');
}, duration);
});
return promise;
};
setTimer(2000).then((res) => console.log(res));
添加回答
举报