简体   繁体   English

我应该如何在退货声明中处理这个有条件的承诺?

[英]How should I deal with this conditional promise in a return statement?

I need to perform several functions, some of which may include asynchronous callbacks (based on conditions) when a button is clicked. 我需要执行几个功能,其中一些功能可能包括单击按钮时的异步回调(基于条件)。

I have a submit button that I do not want to prevent default behavior on to perform these operations (ieepreventDefault()) 我有一个提交按钮, 不想阻止执行这些操作的默认行为(即eprepreventDefault())

Instead, I need to simply return true or false: 相反,我只需要返回true或false:

$('#submitBtn').click(function(e) {
    return mdl.entry(e);
});

var mdl: {
  entry: function(evt) {
    if (condition) {
      return ...
    } else {
      return anotherFunction();
    }
  }
}

function anotherFunction() {
  // This function could potentially involve one or more 
  // asynchronous requests
  some.func(obj).then(function(result) {
    ... do stuff
  });
}

What's the best way to deal with this? 处理此问题的最佳方法是什么? I know I can poll a global variable, or set a variable and trigger a click event: 我知道我可以轮询全局变量,也可以设置变量并触发click事件:

$('#submitBtn').click(function(e) {
    if (!safeToSubmit) {
      e.preventDefault();
      mdl.entry(e); 
      // when finished, it sets safeToSubmit to true
      // and triggers a click on the button 
    } 
});

I hope my issue makes sense. 我希望我的问题有意义。 Above is dummy code. 上面是伪代码。 Probably 10 different functions that conditionally make asynchronous calls. 可能有10个不同的函数有条件地进行异步调用。 Perhaps a best practices question? 也许是最佳做法问题? I can make it work... I just want a better way :) 我可以使它工作...我只想有更好的方法:)

One way to deal with this is to always return a Promise. 解决此问题的一种方法是始终返回承诺。 For synchronous functions instead of return someValue you return Promise.resolve(someValue) 对于同步函数,而不是return someValuereturn Promise.resolve(someValue)

Then you can deal with the return value the same way for everything with something like: 然后,您可以对所有内容使用相同的方式处理返回值,例如:

mdl.entry(e)
.then((ret) => { //do stuff with ret })

EDIT: 编辑:

I am imagining something like this: 我在想像这样的事情:

$('#submitBtn').click(function(e) {
    mdl.entry(e)
    .then((ret) => { /* whatever is supposed to be donw with the return */ })
});

var mdl = {
entry: function(evt) {
    if (condition) {
        var res = someSynchronousFunction(evy)
        return Promise.resolve(res)
    } else {
        return anotherFunction();
    }
}
}

function anotherFunction() {
    return someAsyncFunction(obj).then(function(result) {  
    //... do stuff and return a value
    // someAsyncFunction will return a promise that resolves to this value
    });
}

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

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