【问题标题】:Dojo: Correct way to 'Hitch' scope of deferred typesDojo:正确的方式来“挂断”延迟类型的范围
【发布时间】:2016-10-12 18:50:58
【问题描述】:

我在通过以下 Dojo 小部件的异步结构传递范围时遇到困难:

function callDef(){
//This function has the scope I need
        var deferred = new Deferred();
//try to hitch 'this' to function2
    DojoBaseLang.hitch(this,deferred.resolve(function2(1)));
    deferred.then(DojoBaseLang.hitch(this, function(callback) {
        callback.then(
            function (desiredResult) {
                //How to hitch callDef initial scope to function3?
                function3(desiredResult);
            },
            function (err) {
                // Do something when the process errors out
                console.log(err);
           })
           }),
    function (err) {
        // Do something when the process errors out
        console.log(err);
    }
);
function function2(variable){
//callDef scope not passed by hitch :(
    var dataStucture;
    //deferredFunction is a function which returns type Deferred
     return deferredFunction(hierarchyTableQuery, function(dataSet){
         //some iterative maniupulations will be performed on dataStructure here
         dataStructure = dataSet;

     }).then(function (){
         return dataStructure;
     });
}

function function3(variable){
    //need a way to also have scope in this method
    //doing other stuff
}

如您所见,callDef 首先调用function2,返回一个deferred,完成执行,然后将结果从function2 的dataStructure 对象传递给function3。就延迟/异步行为而言,这一切都很好,问题是被调用的dojo/_base/lang.hitch 函数没有像往常一样在函数之间传递作用域,在这种情况下是从callDeffunction2。我还想将相同的范围传递给function3。我的 require 语句是正确的,并且我有其他非异步 .hitch 调用在同一个小部件/文件中成功。

感谢您的帮助

【问题讨论】:

  • 天啊。它被称为“context”或“receiver”,而不是 scope,看起来 Dojo 文档需要修复。真的,如果你在 2016 年编写代码,你应该使用 the bind method 而不是一些 hitch 函数。或者直接使用箭头函数。
  • 感谢您的意见。你能用箭头函数扩展你所暗示的内容吗?看来,根据Arrow function guide箭头函数表达式与函数表达式相比语法更短,并且不绑定自己的 this、arguments、super 或 new.target
  • 是的,正是这些。您可能还想看看我们关于该主题的规范问题:How to access the correct this / context inside a callback?

标签: javascript asynchronous scope dojo


【解决方案1】:

你可能正在寻找

…
deferred.resolve(DojoBaseLang.hitch(this,function2));
deferred.then(DojoBaseLang.hitch(this, function(callback) {
    callback(1).then(
        DojoBaseLang.hitch(this,function3),
        function (err) {
… // rest of the code

【讨论】:

  • 这行得通,只有当我在第一个 .resolve 调用中使用 .hitch 调用时,JS 解释器抱怨 callback.then() is not a function 否则,完全按照需要工作
  • 请注意,我将 callback.then 更改为 callback(1).then。您的原始代码实际上并没有多大意义(创建立即用函数实现的延迟?),这是我最好的猜测。也许你应该在Code Review 上展示你的整个代码
猜你喜欢
  • 2013-08-13
  • 1970-01-01
  • 2014-11-03
  • 2013-04-14
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
相关资源
最近更新 更多