Node.js script must wait until service starts

I have a node.js script that starts on boot. It uses node -redis to create a client for Redis, but when it boots, Redis is not ready while node is already running. Thus, it gives an exception and terminates the execution.

The first part is as follows:

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

An exception is redis.createClient() on line 3 ( redis.createClient() ).

My solution was to create an infinite loop, create a client in try / catch and, if it succeeds, 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 

In a couple of seconds, this will be the output:

 FATAL ERROR: JS Allocation failed - process out of memory 

How can i solve this? I am looking for a solution that could be in php:

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

setTimeout is asynchronous. JavaScript (and Node.js) has very few functions that wait for something to happen before continuing (like sleep ). Instead, execution continues to the next line immediately, but you pass setTimeout a callback function that runs when it starts.

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

 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 }); 
+3
source

Source: https://habr.com/ru/post/908649/


All Articles