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

时间:2020-01-02 14:36:24

标签: javascript promise

我正在寻找处理这种情况的最佳方法:

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

我虽然使用了存储的回调,但这不是很可读...

4 个答案:

答案 0 :(得分:2)

将常用代码移至功能

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

答案 1 :(得分:1)

与在两个分支中将要执行相同操作的if / else一样,您应将重复的代码放在条件语句之外。使用async/await可以很容易地做到这一点:

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

答案 2 :(得分:0)

您可以创建一个小的对象来为您处理语句,其中还包含所需的功能。这是您可以回收/附加所需的任何功能,并在需要时进行扩展。

    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});

答案 3 :(得分:0)

您可以将首字母转换为诺言

decimal counter = Orders.SelectMany(o => o.Items).Where(i => i.Name == itemName).Distinct().Sum(i => i.Price * i.Quantity);