Node.js 脚本应该在服务运行之前等待 [英] Node.js script should wait before service is running

查看:51
本文介绍了Node.js 脚本应该在服务运行之前等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在启动时启动的 node.js 脚本.它使用 node-redis 为 Redis 创建客户端,但在启动时 Redis 尚未准备好,而节点已经启动.所以,它给出了一个异常并停止执行.

I have a node.js script which starts at boot. It uses node-redis to create a client for Redis, but at boot Redis is not ready while node is already starting. So, it gives an exception and stops executing.

第一部分看起来像这样:

The first part looks like this:

var redis  = require("redis"),
    jobs   = require("jobs"),
    client = redis.createClient(),
    runner = new jobs(client, "job-queue",{});

// Continue using runner

在第 3 行(redis.createClient())抛出异常.

The exception is thrown in line 3 (redis.createClient()).

我的解决方案是无限循环,在 try/catch 中创建客户端,成功时停止循环:

My solution was to make an endless loop, create the client in a try/catch and when successful, stop the loop:

var redis  = require("redis"),
    jobs   = require("jobs"),
    queue  = 'job-queue',
    client = null,
    runner = null,
    createClient = function (redis, jobs, queue) {
        try {
            client = redis.createClient();
            return new jobs(client, queue, {});
        } catch (err) {
            return null;
        }
    };

while(true) {
    setTimeout(function() {
        runner = createClient(redis, jobs, queue);
    }, 1000);

    if (null !== runner) break;
}

// Continue using runner

几秒钟后,这是输出:

FATAL ERROR: JS Allocation failed - process out of memory

我该如何解决这个问题?我正在寻找可能在 php 中的解决方案:

How can I solve this? I am searching for a solution which could be in php:

while (true) {
    $client = createClient($redis, $jobs, $queue);
    if ($client instanceof MyClient) break;
    else sleep(1);
}

推荐答案

setTimeout异步.JavaScript(和 Node.js)很少有函数会在继续之前等待某些事情发生(比如 sleep).相反,执行会立即继续到下一行,但是您传递了 setTimeout 一个回调函数,该函数在它触发时运行.

setTimeout is asynchronous. JavaScript (and Node.js) have very few functions that wait for something to happen before continuing (like sleep). Instead, execution continues to the next line right away, but you pass setTimeout a callback function which is run when it fires.

我会做这样的事情(警告,未经测试):

I would do something like this (warning, untested):

var redis  = require("redis"),
    jobs   = require("jobs"),
    queue  = 'job-queue';

function initializeRedis(callback) {
    (function createClient(){
        var runner;
        try {
            client = redis.createClient();
            runner = new jobs(client, queue, {});
        } catch (e) {}
        if (runner){
            callback(runner);
        } else {
            setTimeout(createClient, 1000);
        }
    })();
};

initializeRedis(function(runner){
    // Continue using runner
});

这篇关于Node.js 脚本应该在服务运行之前等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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