【问题标题】:Using jQuery when with array of promises使用承诺数组时使用 jQuery
【发布时间】:2016-07-24 04:22:06
【问题描述】:

我正在尝试将一系列模板加载到一个数组中,但在使用 jQuery 的 when 方法时遇到了一些问题(基于 this answer

var files = [/*array of file names*/];
var templates = [];
files.forEach(function(file){
    templates.push(
        $.get('/temps/' + file + '.hbs').then(function(temp) {
            console.log('done loading', temp);
        })
    )
});
$.when.apply($, templates).then(function() {
    console.log(arguments); //"undefined"x10
});

为什么不给when 的承诺数组生成我的十个模板的数组?这里出了什么问题?

编辑: 显然,在每个 get 中丢弃 then 方法让我更接近一点:

templates.push($.get('/temps/' + file + '.hbs'));

但是我很好奇我什么时候不能在这里使用then,以及什么时候

templates.push($.get('/temps/' + file + '.hbs')[0]) 

仍然给了我undefineds 的数组。返回数组中的第一个元素是返回的数据。为什么推送第一个元素不起作用?

【问题讨论】:

    标签: javascript jquery promise deferred


    【解决方案1】:

    您正在调用then,它返回另一个承诺。如果您只是想要“副作用”,请改用done

    【讨论】:

      【解决方案2】:

      因为数组中的承诺是undefined 的承诺,而不是模板的承诺。您需要使用

      $.get('/temps/' + file + '.hbs').then(function(temp) {
          console.log('done loading', temp);
          return temp;
      //  ^^^^^^
      })
      

      获取模板的承诺,否则将使用隐式返回值undefined 解析。请记住,then 为回调结果返回一个新的 Promise,而不是原来的 Promise。

      【讨论】:

      • 谢谢。你能看到我的编辑吗?这更正确吗?
      • 这很好用。但是我正在尝试将此数据返回到另一个函数。 $.when.apply($, templates).then(function() { return arguments }); 并将数据存储在另一个变量中。因此,例如,所有 ajax 都将在函数 doAjax() 中,而我尝试执行 var templatesFromAjax = doAjax(),但是在下一行执行 `console.log(templatesFromAjax);
      • 是的,完全不使用then 也是正确的。使用 [0] 没有意义,因为 Promise 没有这样的属性。
      • 您可以使用.then(function(){ return $.map(arguments, function(args) { return args[0]; }); }) 来获取一个ajax 结果数组。与具有多个返回值的承诺相比,jQuery.when 是可怕的。
      • @thomas:可能你在作用域视图中得到了map 回调的arguments,而不是then 回调的arguments
      猜你喜欢
      • 2015-08-06
      • 1970-01-01
      • 2018-02-22
      • 2013-10-06
      • 2021-02-27
      • 2016-07-27
      • 2015-05-15
      • 2012-11-16
      • 1970-01-01
      相关资源
      最近更新 更多