Node.js retrieves data from mongodb and sends it to socket.io, but the order is twisted.

Asked 2 years ago, Updated 2 years ago, 103 views

I thought it would be long if I put the whole sauce, so I cut it and edited it and uploaded it. I'm sorry if it looks messy

for(var index in room.messagelog){
    if(msg.type != 'data'){
            match = urlPattern.exec(msg.msg);
            if(match != null && match.length>1){
                var text = match[0];
                og(text, function(err, meta){
                io.sockets.to(socket.room).emit('message url', msg, meta);
                });
            }else{
                console.log ('General')
                io.sockets.to(socket.room).emit('message', msg);
            }
        }else{
     Data.findOne({'room_name':socket.room,'send_id':email, 'name':msg.msg },function(err, data){
                if(err) console.log(err);
                if(data != null){
                    console.log ('data')
                io.sockets.to(socket.room).emit('data', data,.email,name);
                }
            }); 
        }
}

Like the title, it's a task to send room.messagelog in order and send it to the socket The original array is

data
General
General
General
Data
General
General
General

It's normal when it comes out in this order, but if you turn it around and check it,

General
General
General
General
General
General
General
Data
Data

It comes out in this order. I don't understand how this works for me. What is the problem and how should we deal with it?

node.js socket.io mongodb

2022-09-21 17:43

1 Answers

The order is not guaranteed because the Data.findOne function operates asynchronously.

During the iteration, it does not wait for data to be retrieved from the line running the findOne function, but proceeds immediately to the next line, and the callback function passed to the findOne function as the second factor is executed Someday.

Therefore, the part that does not take the findOne function in the repeat statement is executed first, and the callback function registered in the relatively slow findOne function is executed later.

Because most nodes have this asynchronous form of api, an accurate understanding of the asynchronous code is required.

I think it can be solved by referring to the module below.

Async


2022-09-21 17:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.