简体   繁体   English

有没有一种优雅的方法来避免 Promise 的代码重复?

[英]Is there an elegant way to avoid code duplication with Promise?

I'm looking for the best way to handle this case:我正在寻找处理这种情况的最佳方法:

if (/* condition */) {
  /* do something */
} else {
  asyncFunc().then(/* do the same thing */);
}

I though of using a stored callback but this is not very readable...我虽然使用存储的回调,但这不是很可读......

Move your common code to function将您的通用代码移动到函数中

function someThing() {
/* do something */
}
if (/* condition */) {
  someThing();
} else {
  asyncFunc().then(someThing);
}

Like any if/else where you'll be doing the same thing in both branches, you should put repeated code outside of the conditional.像任何 if/else 一样,你将在两个分支中做同样的事情,你应该把重复的代码放在条件之外。 This can be done easily with async/await like this:这可以通过async/await轻松完成,如下所示:

if (!/* condition */) {
    await asyncFunc();
}
/* do something either immediately or after the asyncFunc resolves */

You could create a small object that handles your statements for you, which also contain the functions you need.您可以创建一个小对象来处理您的语句,其中还包含您需要的函数。 This was you can recycle/append any functionality you need and expand whenever you need to.这是您可以回收/附加您需要的任何功能并在需要时扩展。

    let App = {
        process: function (obj) {
            if (obj.param) {
                App.funcA();
            } else {
                App.asyncThing().then((res) => { App.funcA(res) });
            }
        },
        asyncThing: function () { /*..*/ },
        funcA: function () { /*...*/ },
    }
    App.process({param: true});

您可以将第一种情况转换为承诺

(YourCondition ? Promise.resolve(someValue) : asyncFunc()).then(v => ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM