永远不会调用异步函数的回调 [英] Callback of an asynchronous function is never called

查看:28
本文介绍了永远不会调用异步函数的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个函数,它等待一个异步函数完成它的工作然后返回.

I have this function which waits for an asynchronous function to do its job and then returns.

function synchronous(){
    var notYet = true;

    setTimeout(function(){
        notYet = false;
    }, 1000);

    while(notYet)
        ;

    return "Done synchronously!";
}

console.log(synchronous());

此处函数 synchronous 使用 while 循环停止,直到异步函数的回调(此处为 setTimeout)被执行.但是,回调永远不会被调用(使用回调内的 alert 检查),因此,notYet 将保持 true 并且函数循环将继续永远.那么,为什么回调在 1000 毫秒后没有被调用?

Here the function synchronous stall using the while loop untill the callback of the asynchronous function (here setTimeout) get executed. But, the callback is never called (checked using an alert inside the callback), therefore, notYet will remain true and the function loop will go forever. So, why doesn't the callback get called after 1000 ms?

注意:我不在乎如何将异步函数变成同步函数.我的问题是为什么没有调用回调?

NOTE: I don't care how to make an asynchronous function into a synchronous one. My question is why the callback not getting called?

推荐答案

回调没有被调用,因为唯一可以调用它的线程正在执行无限循环.

The callback isn't getting called because the only thread that can call it is tied up doing your infinite loop.

在浏览器中,JavaScript 在单个主 UI 线程上运行(加上您想要创建的任意数量的网络工作线程).该线程在作业队列上运行:它选择要执行的作业(例如,处理单击),执行该作业,然后返回以等待下一个作业.你用无限循环阻塞了那个线程.计时器在作业队列中安排回调(可能是特定于实现的),但线程永远不会完成当前作业(称为无限循环的作业),因此它永远不会选择下一个作业.

In browsers, JavaScript runs on a single main UI thread (plus as many web workers as you want to create). That thread runs on a job queue: It picks up a job to do (for instance, processing a click), does the job, and then yields back to wait for the next job. You're blocking that one thread with the infinite loop. The timer schedules the callback in the job queue (probably, that's implementation-specific), but the thread never finishes the current job (the one that called your infinite loop) and so it never picks up that next job.

NodeJS 还可以在单​​个线程中运行您的代码,并且执行相同的操作.(并非所有环境都这样,但我不知道任何带有 setTimeout 的环境不会在请求它的同一线程上安排计时器回调.)

NodeJS also runs your code in a single thread and so does the same thing. (Not all environments do, but I'm not aware of any with setTimeout that don't schedule the timer callback on the same thread that requested it.)

这篇关于永远不会调用异步函数的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆