this.async()在JavaScript中做什么

Ton*_*ony 9 javascript asynchronous

保持在代码中看到这种模式,但在google或SO中找不到任何引用,很奇怪.有人能指点我参考this.async()函数吗?

  var done = this.async();
  // ...
  $.get(path, function(contents) { // or some other function with callback
    // ...
    done(JST[path] = tmpl);
  })
Run Code Online (Sandbox Code Playgroud)

Bri*_*ark 17

var done = this.async()并且done(blah)是一个聪明的技巧,可以$.get在同步函数中返回从异步调用(例如)中获取的值.

我们来看一个例子:

var getText = function() {
  return "hello";
};
var text = getText();
Run Code Online (Sandbox Code Playgroud)

这是一个非常简单的函数调用,所以这里没有谜题.但是,如果需要在getText()函数中异步获取文本,该怎么办?

var getText = function() {
  return $.get('<some-url>', function(text) {
    return text;
  });  // ??????
};
Run Code Online (Sandbox Code Playgroud)

呼叫getText()不会返回您想要的文本.它返回jquery的promise对象.

那么我们如何getText()返回它从$.get()调用中得到的文本?

var getText = function() {
  var done = this.async();
  $.get('<some-url>', function(text) {
    done(text);
  });
};
var text = getText();  // you get the expected text
Run Code Online (Sandbox Code Playgroud)

魔术吧?

我还不知道电话的内部工作this.async().我不知道是否有一个库提供该功能,但你可以看到Backbone.LayoutManager使用这个技巧https://github.com/tbranyen/backbone.layoutmanager/blob/master/backbone.layoutmanager.js(搜索for this.async).

此外,Tim Branyen(骨干布局管理员的作者)在他的视频教程(http://vimeo.com/32765088 14:00 - 15:00)中简要介绍了它.在视频中,蒂姆说本阿尔曼提出了这个伎俩.看看这个以及https://github.com/cowboy/javascript-sync-async-foreach

我认为混合异步和同步功能是一个非常巧妙的技巧.

干杯,


Tom*_*icz -3

这是解决this回调内部转义问题的一种方法。如果没有这个额外的引用,代码将如下所示:

$.get(path, function(contents) { // or some other function with callback
  //Wrong! `this` might no longer point to your object
  this.done(JST[path] = tmpl);
})
Run Code Online (Sandbox Code Playgroud)

很遗憾!内部响应回调与外部this不同。this事实上,它可以是任何东西,具体取决于什么$.get(调用回调使用)决定它是什么。大多数人使用that出于相同目的命名的额外参考:

var that = this;
// ...
$.get(path, function(contents) { // or some other function with callback
  // ...
  that.async(JST[path] = tmpl);
})
Run Code Online (Sandbox Code Playgroud)

这种模式看起来也合理且可读。

哦,如果您对这种语法感到好奇:

done(JST[path] = tmpl)
Run Code Online (Sandbox Code Playgroud)

这是用作表达式的赋值。赋值的值在右边,所以这段代码等价于:

JST[path] = tmpl;
done(tmpl);
Run Code Online (Sandbox Code Playgroud)

  • -1:这并没有回答有关“this.async()”的问题,而是讨论了问题中甚至没有出现的问题。我很困惑为什么@Tony 接受这个答案。 (9认同)