【问题标题】:How to change argument of function passed as reference?如何更改作为参考传递的函数的参数?
【发布时间】:2018-01-16 00:24:29
【问题描述】:

我在这里有一个承诺链,我正在传递对函数的引用,然后将参数传递给它。
当我们到达第 6 个.then() 时,我们会抛出一个错误。我想要Error 格式为Error.message,所以我得到文本OH NOES 而不是实际错误。
我当然可以在 alwaysThrows 函数中执行此操作,也可以将函数传递给方法,例如Catch(function(error) { return error.message})。但是我想知道是否有一种方法可以操纵传递给 console.log 的参数,而无需将函数传递给它,但将其保留为对 console.log 的引用?

function alwaysThrows() {
    throw new Error('OH NOES');
}
function iterate(num){ 
    console.log(num)
    return num + 1;
}
promise = Promise.resolve(1)
.then(iterate) // 1
.then(iterate) // 2
.then(iterate) // 3
.then(iterate) // 4
.then(iterate) // 5
.then(alwaysThrows)
.then(iterate)
.then(iterate)
.then(iterate)
.then(iterate)
.then(iterate)
.catch(console.log)

【问题讨论】:

  • 您想更改传递给console.log 的值,但不更改传递给console.log 的输入值,就像.catch(error => Promise.reject(error.message)) 一样?不,那是不可能的。作为一种限制,似乎也很随意。
  • .catch(error => console.log(error.toString()))
  • @Ryan 是的,我认为 .call 或 .bind 和/或一些奇怪的参数解构可能会有一些解决方案。好奇。

标签: javascript promise


【解决方案1】:

只需创建一个通用函数来处理错误。

在这里,我创建了一个名为 niceLog 的简单函数,并将其放入 catch 回调中。

e.message || e.toString() 只是让它显示OH NOES,否则它会显示Error: OH NOES,如果没有消息属性,它将回退到 toString。

function niceLog(e) {
  console.log(e.message || e.toString());
}

function alwaysThrows() {
    throw new Error('OH NOES');
}
function iterate(num){ 
    console.log(num)
    return num + 1;
}
promise = Promise.resolve(1)
.then(iterate) // 1
.then(iterate) // 2
.then(iterate) // 3
.then(iterate) // 4
.then(iterate) // 5
.then(alwaysThrows)
.then(iterate)
.then(iterate)
.then(iterate)
.then(iterate)
.then(iterate)
.catch(niceLog)

【讨论】:

  • 谢谢,这也有效!更多的是寻找一种不向其传递实际函数但操纵参数的方法,但我现在明白 javascript 没有办法。知道 javascript 不能做什么也很高兴 :-)。
猜你喜欢
  • 2015-12-04
  • 2012-01-17
  • 2019-09-23
  • 2019-11-29
  • 2014-03-05
  • 2019-12-28
  • 2011-12-15
  • 2019-04-25
  • 1970-01-01
相关资源
最近更新 更多