简体   繁体   English

为什么我的超时要等到等待完成后才出现,而我的日志却没有?

[英]Why does my timeout wait until after the await completes but my log does not?

If I have something like this setup: 如果我有这样的设置:

<-- language: lang-javascript --> <-语言:lang-javascript->

console.clear();

// noprotect

const fetchSomething = () => new Promise((resolve) => {
    setTimeout(() => resolve('future value'), 500);
});

async function asyncFunction() {
    const result = await fetchSomething();
    console.log('waiting');
    setTimeout(()=>console.log('waiting?'), 250);
    return result + ' 2';
}

asyncFunction().then(result => console.log(result));

And my output looks like: 我的输出看起来像:

"waiting"
"future value 2"
"waiting?"

I would expect the waiting? 我希望waiting? to execute before the result completes, but for some reason it waits on the function. 在结果完成之前执行,但是由于某种原因,它会等待该函数。 What makes one wait but the other execute? 是什么让一个人等待而另一个人执行?

It is a feature of Asynchronous programming. 它是异步编程的功能。

You have to add await and wrap your setTimeout(()=>console.log('waiting?'), 250); 您必须添加await并包装setTimeout(()=>console.log('waiting?'), 250); with a function which returns Promise in order to make it look like it was evaluated continuously. 带有一个返回Promise的函数,以使其看起来像被连续评估。

Something like: 就像是:

await ((ms) =>{
        console.log('waiting?');
        return new Promise(resolve => setTimeout(resolve, ms));
    })(250);

Or: 要么:

await (() => new Promise(resolve => setTimeout(()=>{
    console.log('waiting?');
    resolve();
}, 250)))();

Mind you, JS has a single threaded run-time engine, so it interrupts evaluation when original script reaches it's end. 请注意,JS具有单线程运行时引擎,因此当原始脚本到达末尾时它会中断评估。

And function in setTimeout(function, timeout) is evaluated by JS when it has a first chance and time is right. 当JS第一次遇到机会且时间合适时, setTimeout(function, timeout)由JS评估。

So your function was interrupted twice and was resumed twice. 因此,您的功能被中断了两次,并被恢复了两次。

The call to log "waiting?" 通话记录为“等待中”? is started by a setTimeout after the await has finished, so after the 500ms in fetchSomething have already passed. await完成后由setTimeout启动,因此fetchSomething的500ms已经过去。 It will only execute 250ms after fetchSomething has returned. fetchSomething返回后,它将仅执行fetchSomething That is enough time for asyncFunction to return. 这足以让asyncFunction返回。

If you want to see a different behaviour, start the timer for logging "waiting?" 如果要查看其他行为,请启动计时器以记录“正在等待?” before calling await: 在呼叫等待之前:

async function asyncFunction() {
  setTimeout(()=>console.log('waiting?'), 250);
  const result = await fetchSomething();
  console.log('waiting');
  return result + ' 2';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM