【问题标题】:Does something like this work in asynchronous code?像这样的东西在异步代码中有效吗?
【发布时间】:2011-08-30 05:43:36
【问题描述】:
regular = 'a string';
enriched = enrichString(regular);
sys.puts(enriched);

function enrichString(str){
    //run str through some regex stuff or other string manipulations
    return str;
}

现在它似乎正在做我希望它会做的事情,但我不知道它是否安全。这有时会导致未定义吗?我需要做类似的事情吗:

regular = 'a string';
enriched = enrichString(regular, function(data){sys.puts(data);});

function enrichString(str, cb){
    //run str through some regex stuff or other string manipulations
    cb(str);
}

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery asynchronous node.js callback


    【解决方案1】:

    不,你应该没事的。计算代码的直接运行本质上不是异步的。当某些操作涉及外部资源(文件 I/O、网络操作、某些操作系统交互等)时,需要回调。

    【讨论】:

      【解决方案2】:

      只有在进行异步非阻塞调用时才需要回调。

      var string = "foo",
          new_string = enrich(foo);
      
      doStuff(new_string);
      

      如果enrich 被阻塞是安全的。例如

      function enrich(str) {
          // do regex stuff with str
      
          // manipulate it
      
          return str;
      }
      

      正在阻塞,所以这样做是安全的。在哪里

      function enrich(str) {
          // get some data from the database.
      
          // store the string in a file.
      
          return str;
      }
      

      使用非阻塞 IO,不安全。你想做的是这样的:

      function enrich(str, cb) {
          // get some data from the database.
      
          // store the string in a file.
      
          return cb(str);
      }
      
      var string = "foo",
          new_string = enrich(foo, function (str) {
              doStuff(new_string);
          });
      

      注意

      enriched = enrichString(regular, sys.puts(data));

      不起作用,因为您将 sys.puts(data) 的返回值作为函数参数传递(数据也未定义!)

      你需要传入一个函数。

      【讨论】:

      • @Pointy 你仍然击败了我,通过对答案进行旧的增量更改。
      • 啊,是的,在 sys.puts() 中传递的那个例子搞砸了——感谢您提供的所有重要信息
      【解决方案3】:

      只是为了增加 Pointy 的响应,人们有时会使用 process.nextTick(或在浏览器中的 setTimeout(fn,0))强制执行异步行为 - 这会强制当前执行上下文屈服。例如:https://github.com/caolan/async/blob/master/lib/async.js#L408-410

      【讨论】:

      • setTimeoutsetInterval
      猜你喜欢
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 2014-02-08
      • 1970-01-01
      • 2013-07-30
      • 2014-09-29
      • 1970-01-01
      相关资源
      最近更新 更多