如何包装异步调用以使其行为同步? [英] How can I wrap up an asynchronous call to behave synchronously?

查看:51
本文介绍了如何包装异步调用以使其行为同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,这就是我使用node-mysql执行查询的方式

Currently, this is how I perform a query using node-mysql

client.query( sql, function( error, result ) {
  console.dir( result );
});

我想同步执行此操作

var result = client.querySync( sql );
console.dir( result );

我理解为什么阻塞节点不好,但是我(几乎)已经长大了,知道什么时候可以,什么时候不可以.我只打算在任何事件循环之外的初始化阶段进行同步调用.

I understand why blocking in node is bad, but I'm (almost) grown up enough to know when it's okay and when it's not. I only intend to make synchronous calls at the initialisation stage, outside of any event loops.

有人知道我能做到这一点吗?

Does anybody know how I can achieve this please?

编辑...

类似...

client.querySync = function( sql )
{
    var called = false;
    var result;

    while ( typeof result == 'undefined' ) {
        if ( ! called ) {
            called = true;
            this.query( sql, function( error, _result ) {
                result = { error: error, result: _result };
            });
        };
    }

    return result;
};

推荐答案

您提出的解决方案(在您的编辑中)将无法正常工作,因为您永远不会放弃线程(因此永远不会调用回调,因此变量永远不会被设置,因此您的循环永不中断).节点不是多线程的-在任何时候只有一个线程执行javascript.除了从正在运行的任何代码中返回之外,没有其他方法可以产生该线程.

Your proposed solution (in your edit) won't work because you never give up the thread (so the callback can never be called, so the variable can never be set, so your loop never breaks). Node is not multi-threaded - there is only ever one thread executing javascript at any one time. There is no way to yield that thread except by returning from whatever code is running.

因此,您无法做自己想做的事.您可以尝试使用一些将同步代码重新编写为异步的解决方案,但我个人发现这种方法并不值得付出努力,最好还是硬着头皮做,带有回调的所有东西(随着时间的流逝,痛苦消失了:).

So, you can't do what you want to do. You could try to use some of the solutions that re-write your sync code into async behind the scenes, but I've personally found that approach isn't really worth the effort -- that's it better to just bite the bullet and just do everything with callbacks (over time the pain subsides :).

这篇关于如何包装异步调用以使其行为同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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