node.js socket.io socket.set 和 socket.get - 回调参数是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10360110/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:37:47  来源:igfitidea点击:

socket.io socket.set and socket.get - what is the callback argument for?

node.jssocket.io

提问by Karl Keefer

I just want to attach some variables to my sockets, but I don't understand the .get and .set methods. They both have a third argument for a callback. Can this be omitted? What is it for?! Does the callback itself intherit arguments?

我只想将一些变量附加到我的套接字,但我不理解 .get 和 .set 方法。它们都有用于回调的第三个参数。这个可以省略吗?这是为了什么?!回调本身是否继承了参数?

My best guess is that it's there for when socket.io isn't using memory store but is saving this stuff somewhere else and needs an error checking callback.

我最好的猜测是,当 socket.io 不使用内存存储但将这些东西保存在其他地方并且需要错误检查回调时,它就在那里。

socket.on('set nickname', function (name) {
    socket.set('nickname', name, function (arguments) {
      doSomethingMysterious();
    });

I'm using socket.io 0.9.x

我正在使用 socket.io 0.9.x

The function is defined in socket.js

该函数在 socket.js 中定义

/**
 * Stores data for the client.
 *
 * @api public
 */

Socket.prototype.set = function (key, value, fn) {
  this.store.set(key, value, fn);
  return this;
};

采纳答案by mihai

setand getare asynchronous. The callback will be called when these operations are completed. You can omit it, or you can use it for whatever purpose you like, not just error handling.

set并且get是异步的。当这些操作完成时将调用回调。你可以省略它,或者你可以将它用于任何你喜欢的目的,而不仅仅是错误处理。

回答by caike

The getand setfunctions on the socket object were removed in version 1.x. The proper way to store and retrieve values now is through properties on the socket object, like so:

getset插座对象上的功能在1.x版本中被拆除。现在存储和检索值的正确方法是通过套接字对象上的属性,如下所示:

socket.on('set nickname', function (name) {
  socket.nickname = name;
});

As seen on the example code from the official repo.

官方存储库中示例代码所示。