用于从回调函数返回值的方法或设计模式

method or design pattern for returning values from callback functions

本文关键字:方法 设计模式 返回值 回调 函数 用于      更新时间:2023-09-26

所以我正在使用回调函数,当然,如果我console.log返回参数它显示数据,但是我如何将返回数据分配给外部变量。下面的代码是我试图实现的,但它返回未定义。是否存在实现这一目标的设计模式?我试着寻找一个答案,但不确定要寻找什么,或者它甚至是可能的?

var person = (function () {
  function message(messages, callback) {
      chrome.runtime.sendMessage(messages, function(response) {
          callback(response);
      });
  }
  return {
    male: message
  };
})();

var me = person.male({
  mydata: {
    firstname: 'john',
    lastname: 'doe'
  }
}, function (person) {
  // of course this works
  console.log(person);
  return person;
});
// does not work
console.log(me);

在你的特定代码中,你已经证明了你的回调是由person.male()方法调用的,但是它完全取决于person.male()函数的设计,它对该回调的返回值做了什么。

如果person.male()异步调用回调(例如将来的某个时候),那么它就没有机会从person.male()返回您的返回值。如果一切都是同步的,那么回调的返回值只有在person.male()被写入时才会从person.male()返回。既然它没有这样做,那么它显然不是这样写的,而且person.male()代码之外的任何代码都不会改变它的工作方式。


现在,您已经显示了person.male()的代码,我们可以看到回调是由chrome.runtime.sendMessage()函数调用的,因此回调的返回值返回到该函数中。person.male()不是写来做任何与回调的返回值有关的事情。

并且,根据chrome.runtime.sendMessage()的目的判断,我会说它可能异步调用回调,这意味着它是在person.male()已经返回之后调用的,所以没有办法从person.male()返回的回调中获得返回值,因为person.male()甚至在回调调用之前返回。


作为侧边栏,您可以将稍微复杂的person定义替换为更容易遵循的代码:

var person = {
    male: function(messages, callback) {
        chrome.runtime.sendMessage(messages, callback);
    }
};

回调函数可以直接设置"outside"变量。但是,如果回调是异步调用的,那么在此之前'me'将是未定义的:

var me;
person.male({
  mydata: {
    firstname: 'john',
    lastname: 'doe'
  }
}, function (person) {
  console.log(person);
  me = person;
});
// 'me' will be undefined until the callback is called.
console.log(me);

这是异步代码,所以在得到函数的结果之前不要延迟主线程。在您的示例中,有必要访问console.log(me)的值。