【问题标题】:(intermediate value).then is not a function(中间值).then 不是函数
【发布时间】:2019-05-05 15:31:24
【问题描述】:

我是 Javascript 的新手。 由于一些遗留系统,目前我正在将一些 ES6 代码转换回 ES5 代码。 我转换了以下代码:

$row.find('.gridCellDetailAction')
 .each((i, elem) => $translate('Grid.Show' + $(elem).attr('data-title') + 's')
.then(trans => $(elem).attr('title', trans)));

到这里

   $row.find('.gridCellDetailAction')
        .each(function (i, elem) {
              $translate('Grid.Show' + $(elem).attr('data-title') + 's')
   }.then(function (trans) { $(elem).attr('title', trans) }));

现在我收到以下错误:

(中间值).then 不是函数

现在我知道我对then 做错了。但是我怎样才能得到同样的结果呢?

【问题讨论】:

  • babel 可以帮忙吗?
  • 我可以看到一个右括号 } 在错误的位置,.then 之前的那个。那个应该放在最后一个)之前。

标签: javascript ecmascript-6 ecmascript-5


【解决方案1】:

通过一些格式,您可以轻松看出差异。 一次是在 $translate 的结果上调用 then,另一次是在函数定义上调用 then

$row.find('.gridCellDetailAction')
.each(
  (i, elem) => {
    $translate(
     'Grid.Show' + $(elem).attr('data-title') + 's'
    )
    .then(
      trans => $(elem).attr('title', trans)
    )
  }
);
$row.find('.gridCellDetailAction')
.each(
  function (i, elem) {
    $translate('Grid.Show' + $(elem).attr('data-title') + 's')
  }// <-- The error is here
  .then(
    function (trans) { 
      $(elem).attr('title', trans) 
    }
  )
);

这是正确的:

$row.find('.gridCellDetailAction')
.each(
  function (i, elem) {
    $translate('Grid.Show' + $(elem).attr('data-title') + 's')
    .then(  //Now then is called on the result of $translate
      function (trans) { 
        $(elem).attr('title', trans) 
      }
    )
  }
);

【讨论】:

  • 很高兴能为您提供帮助。您应该将此答案标记为正确,以便其他用户可以轻松找到它
【解决方案2】:

出了什么问题:
从您的代码中,我将删除 $row.find('.gridCellDetailAction').each();

function (i, elem) {
    $translate('Grid.Show' + $(elem).attr('data-title') + 's')
}
.then(function (trans) { $(elem).attr('title', trans) })

此代码似乎错误; 所以,我们需要把.then(function (trans) { $(elem).attr('title', trans) })放在function()


完整代码:

$row.find('.gridCellDetailAction')
    .each(function (i, elem) {
        $translate('Grid.Show' + $(elem).attr('data-title') + 's')
            .then(function (trans) { $(elem).attr('title', trans) });
    });

【讨论】:

  • 这不是很有帮助。您应该尝试解释为什么他/她的代码不起作用以及您所做的与他/她不同的地方
猜你喜欢
  • 1970-01-01
  • 2020-03-14
  • 2019-02-10
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 2017-10-07
  • 2021-07-24
相关资源
最近更新 更多