【问题标题】:Thenable function. Different return type on call or `await` /`then` appliedthenable 函数。应用了不同的返回类型 on call 或 `await` /`then`
【发布时间】:2021-09-27 23:32:46
【问题描述】:

在js中是简单的例子

function thenable() {

    return ['just function']
}
thenable.then = (resolve) => {
  resolve('like a Promise')
}
(async function main() {
  //behave like a function 
  const functionResult = thenable()
  //behave like a Promise
  const promiseLikeResult = await thenable
})()

是否可以使用打字稿键入此行为,当您调用它就像函数时它返回 string[](['just function']) 当 thenawait 应用它返回 string ('like a承诺')?

【问题讨论】:

  • 我想知道这是不是X/Y problem。为什么你希望函数做两件截然不同的事情?

标签: javascript typescript generics types


【解决方案1】:

不,你不能。返回其值时,该函数无法知道您是否要在其上查找 then(这是显式调用 thenawait 两者都做的事情)。

您可以做很多事情,但它们似乎过于复杂,并且像潜在的维护问题(相对于只有两个函数,每个函数都有一个明确定义的行为)没有一个真正强大的用例:

  • 您可以返回一个函数,该函数返回一个上面也有 then 的函数,然后让返回的函数做一件事,而上面的 then 做另一件事。

  • 您可以返回一个带有then 方法(例如,thenable)的对象,该方法也实现了toStringvalueOf,与调用then 时所做的事情不同。但这依赖于调用代码来触发这些方法(显式或隐式)。

  • 您可以返回一个 thenable 对象,该对象还具有 now 方法或类似方法,调用代码可以使用该方法在不是 Promise 时获取您想要返回的值。

在这三个中,第三个在我看来可能是最清晰和最容易维护的,但我仍然倾向于两个独立的功能。

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 1970-01-01
    相关资源
    最近更新 更多