如何才能让该函数变成一个同步的?

2023-06-16 318 0

async function f1(){
    await setTimeout(()=>{
        console.log('2');
    },3000);
}
console.log('1');
f1();
console.log('3');

结果是:
1
3
2

明明我上面已经声明f1为同步的了,为何最后一个3不等f1函数执行完就跳出来了?
我想要得到的结果是:
1
2
3

function delay(interval) {
  return new Promise(resolve => setTimeout(resolve, interval));
}
async function f1(){
    await delay(3000);
    console.log('2');
}
console.log('1');
await f1();
console.log('3');

这样不仅清晰易读,也更加符合 异步编程范式

async function f1(){
    await new Promise((r)=>{
      setTimeout(()=>{
        console.log('2');
        r()
        },3000)
    });
}
;(async ()=>{
    console.log('1');
    await f1();
    console.log('3');
})()
(async () => {
function f1() {
return new Promise(resolve => {
setTimeout(() => {
console.log("2");
resolve();
}, 3000);
});
}
console.log('1');
await f1();
console.log('3');
})();

首先你对 f1 函数的定义是有问题的,需要稍加修改,

function f1() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('2');
            resolve();
        }, 3000)
    });
}

其次,调用异步函数并需要等待时需要添加 await 语法糖

(async () => {
    console.log('1');
    await f1();
    console.log('3');
})();

回答

相关文章

nuxt2部署静态化和ssr的时候访问首页先报404再出现首页为什么?
`clip-path` 如何绘制圆角平行四边形呢?
多线程wait方法报错?
VUE 绑定的方法如何直接使用外部函数?
vue2固定定位该怎么做?
谁有redis实现信号量的代码,希望借鉴一下?