简体   繁体   English

带插座的回路 function 不起作用 - WebSocket

[英]Loop with socket function doesn't work - WebSocket

I have a socket endpoint, that I connect to and send a message to get a user.我有一个套接字端点,我连接到该端点并发送一条消息以获取用户。 I used this code to do it:我用这段代码来做到这一点:

import generateConnection from './generate-connection';

export async function fetchUser(id: number) {
  return new Promise(function (resolve) {
    const connection = generateConnection();
    connection.onopen = () => {
      connection.send(
        JSON.stringify(
          '{"msg":"connect","version":"1","support":["1","pre2","pre1"]}',
        ),
      );
      connection.send(
        JSON.stringify(
          `{"msg":"method","id":"1","method":"Users.getUser","params":[${id}]}`,
        ),
      );
      console.log('Connected');
    };
    connection.on('message', async (event) => {
      const data = event.toString();
      if (data[0] == 'a') {
        const a = JSON.parse(JSON.parse(data.substring(1))[0]);
        if (a.msg == 'result') {
          if ('error' in a) {
            console.log('Error' + a.error.msg);
            return null;
          } else {
            resolve(a.result);
          }
        }
      }
    });
    connection.on('error', function (error) {
      console.log('Connection Error: ' + error.toString());
    });
    connection.on('close', function () {
      console.log('echo-protocol Connection Closed');
    });
  });
}

const fetchAllUsers = async () => {
  for (let i = 0; i < 100; i++) {
    const user: any = await fetchUser(i);
    console.log(user.name);
  }
};
fetchAllUsers();

I get the following result:我得到以下结果:

Connected
Jack

It just give me the first user and it stop on the second.它只是给了我第一个用户,然后在第二个用户上停止。

I have no control over the socket and I want to be able to fetch all 5000 users each day to be synced.我无法控制套接字,我希望每天能够获取所有 5000 个用户进行同步。

I'm Using WebSocket for this problem.我正在使用 WebSocket 来解决这个问题。

If you have any proposition other than this method, I'm all ears:D如果您有除此方法以外的任何建议,我会全神贯注:D

To explain more:解释更多:

1 - I want to open a connection 1 - 我想打开一个连接

2 - Send a message 2 - 发送消息

3 - get Result 3 - 得到结果

4 - Add to Array or db 4 - 添加到数组或数据库

5 - When finished, close the connection. 5 - 完成后,关闭连接。

6 - repeat 6 - 重复

Why would you close the connection every time?为什么每次都要关闭连接? An open connection allows you to send many messages.开放的连接允许您发送许多消息。 But maybe it is easier to:但也许更容易:

connection.close()

// right before:
resolve(a.result);

If that didn't work maybe it's time to send more then one request per connection.如果这不起作用,也许是时候为每个连接发送一个以上的请求了。 Try this (I'm a little rusty with promises so I hope you get the idea and improve it)试试这个(我对承诺有点生疏,所以我希望你能理解并改进它)

 import generateConnection from './generate-connection'; export async function fetchAllUsers() { var total = 100; var returned = 0; var all_results = []; return new Promise(function(resolve) { const connection = generateConnection(); connection.onopen = () => { connection.send( JSON.stringify( '{"msg":"connect","version":"1","support":["1","pre2","pre1"]}', ), ); for (var i = 0; i < total; i++) { connection.send( JSON.stringify( `{"msg":"method","id":"1","method":"Users.getUser","params":[${i}]}`, ), ); } console.log('Connected'); }; connection.on('message', async(event) => { const data = event.toString(); if (data[0] == 'a') { const a = JSON.parse(JSON.parse(data.substring(1))[0]); if (a.msg == 'result') { if ('error' in a) { console.log('Error' + a.error.msg); return null; } else { console.log(a.result.name); all_results.push(a.result); returned++; if (returned == total) { resolve(all_results); } } } } }); connection.on('error', function(error) { console.log('Connection Error: ' + error.toString()); }); connection.on('close', function() { console.log('echo-protocol Connection Closed'); }); }); } fetchAllUsers();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM