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

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

问题描述

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

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());

在这里,使用while循环暂停函数synchronous,直到执行异步函数(此处为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线程上(加上您要创建的Web工作者数).该线程在作业队列上运行:它拾取要执行的作业(例如,处理单击),执行该作业,然后让其返回以等待下一个作业.您正在使用无限循环来阻塞那个线程.计时器在作业队列中安排回调(可能是特定于实现的),但是线程永远不会完成当前作业(称为无限循环的那个作业),因此它永远不会拿起下一个作业.

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天全站免登陆