如何使用承诺执行同步函数还是同步函数,如何有效地调用通用函数?

发布于 2025-01-30 05:21:35 字数 927 浏览 4 评论 0 原文

无论调用同步函数,还是调用异步函数,我都需要调用一个共同的函数。

这就是我首次写的方式,但这是不正确的,因为 foo 将在均匀函数完成之前调用。

function main(element) {
  if (element.id === 'sync') {
    syncFunction();
  } else {
    asyncFunction();
  }
  foo();
}

因此,我想到了这一点,但是在这里,我觉得我正在重复 foo 的电话。有更好的方法吗?

function main(element) {
  if (element.id === 'sync') {
    syncFunction();
    foo();
  } else {
    asyncFunction().then(() => {
      foo();
    });
  }
}

我可以使用。有没有一种方法可以更好地使用承诺写这件?

I need to call a common function whether synchronous function is invoked or asynchronous function is invoked.

This is how I first wrote but this is not correct as foo will be called before asynchronous function is completed.

function main(element) {
  if (element.id === 'sync') {
    syncFunction();
  } else {
    asyncFunction();
  }
  foo();
}

So, I came up with this but here I feel like I am repeating the call to foo too many times. Is there a better way?

function main(element) {
  if (element.id === 'sync') {
    syncFunction();
    foo();
  } else {
    asyncFunction().then(() => {
      foo();
    });
  }
}

I could use async/await and refactor this even better but where this code eventually will run doesn't support it. Is there a way to better write this using promises?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晒暮凉 2025-02-06 05:21:35

如果将呼叫的结果放入 Promise.resolve()中,则可以无条件地将.。

function main(element) {
    Promise.resolve((element.id === 'sync' ? syncFunction : asyncFunction)())
        .then(foo);
}

If you put the result of the call into a Promise.resolve(), you can chain .then onto it unconditionally.

function main(element) {
    Promise.resolve((element.id === 'sync' ? syncFunction : asyncFunction)())
        .then(foo);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文