简体   繁体   English

Javascript ES6 Promise函数选项

[英]Javascript ES6 Promise Function Options

I have an async function which can call one of multiple other async functions; 我有一个异步函数,可以调用多个其他异步函数之一; I can split this up into multiple .then.catch chains, but I'm wondering if I can merge them together somehow. 我可以将其拆分为多个.then.catch链,但是我想知道是否可以通过某种方式将它们合并在一起。 What I have is: 我所拥有的是:

return new Promise((resolve, reject) => {
    if (payload.method === 'a')
        doFunctionA(arg)
        .then((x) => resolve())
        .catch((error) => reject())
    else if (payload.method === 'b')
        doFunctionB()
        .then((x) => resolve())
        .catch((error) => reject())
});

That's simplified, but is there another way to write this so that the then and catch is only written once? 简化了,但是还有另一种写方法,那么then和catch只写一次吗? Like: 喜欢:

return new Promise((resolve, reject) => {
    var f = (payload.method === 'a' ? doFunctionA(arg) : doFunctionB());
    f()
    .then((x) => resolve())
    .catch((error) => reject())
});

Since doFunctionA and doFunctionB already return Promises , you don't have to wrap them in another Promise : 由于doFunctionAdoFunctionB已经返回Promises ,因此您不必将它们包装在另一个Promise

(payload.method === 'a' ? doFunctionA : doFunctionB)(arg)
  .then((x) => resolve())
  .catch((error) => reject())

Yes. 是。 You are very close to the right way, except you are calling f twice. 除了您两次调用f之外,您都非常接近正确的方法。 Try something like : 尝试类似的东西:

return new Promise((resolve, reject) => {
    (payload.method === 'a' ? doFunctionA : doFunctionB)(arg)
        .then((x) => resolve())
        .catch((error) => reject())
    ;
});

Still better is to return the function as suggested by @Patrick 更好的是返回@Patrick建议的功能

return (payload.method === 'a' ? doFunctionA : doFunctionB)(arg);

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

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