How to Resolve callbacks (1)

The Node language is full of callbacks, such as the common module Request

var a;
request ( option, function(error, response, body){
    a = body;
})
console.log(a)
Copy the code

In this case, undefined will be printed. When we send a request, the code will execute asynchronously, and when we reach console.log(a), the request method may not have executed yet. The simplest way is to execute the callback function.

var a;
function getBody (callback){
    request (option, function(error, response, body){
    a = body
    callback(a)
})
}

getBody(function(a)){
    console.log(a)
}

Copy the code

This will pass the value from the callback to the function that is now required. A callback is defined that returns a, which is returned after execution in the request.

How to use node + Redis + socket. IO countdown program

When there are many customers and many customer service (each customer can only contact one customer service), it may choose to set up a timer for the current user according to some state of the customer, and trigger this timer when the time is up to inform the customer and customer service. However, when there are too many users, it is not possible to set up a timer for each user, so here is how to use a timer to complete the timer for all users. The main functions used are setTimeout, clearTimeout, and Node reids tools. Simple configuration of Redis, and secondly, setup of Node, which pretend you know the.socket. IO assumption. This is about design and implementation.

Here’s what happens in practice

  • A lot of people, Cus1, Cus2… With Ser1 Ser2…
  • Cus1<=>Ser1 Cus2<=>Ser2 Cus3<=>Ser3…
  • SocketId, Ser1. SocketId, Cus2. SocketId…