简体   繁体   English

如何将 try catch function 变成 promise 并使用 promise.all

[英]how to turn try catch function into promise and use promise.all

In Reactjs, I have two try-catch functions listed as below, and I need to wrap them into a promise.all function. Could anyone tell me how please?在 Reactjs 中,我有两个 try-catch 函数如下所示,我需要将它们包装成一个 promise.all function。谁能告诉我怎么办? I know first I have to turn those two functions into promise, but how?我首先知道我必须将这两个函数变成 promise,但是怎么做呢?

  function one(){
    let isValid = true;
    ...
    if(isValid){
      try{
       const response = await AA.sendMsg({XX})
       return response
       }catch(e){
        console.log(e)
        }
      }
    }
function two(){
    let isValid = true;
    ...
    if(isValid){
      try{
       const response = await BB.sendMsg({YY})
       return response
       }catch(e){
        console.log(e)
        }
      }
    }

sendMsg already returns a Promise (at least, it should, if it doesn't then it makes no sense to use await or introduce Promises). sendMsg已经返回 Promise (至少,它应该返回,如果没有返回,那么使用await或引入 Promises 就没有意义)。

Wrapping then in extra Promises would be an anti-pattern.然后用额外的 Promise 包装将是一种反模式。 Don't do that.不要那样做。

Just pass them to Promise.all:只需将它们传递给 Promise.all:

const [responseAA, responseBB] = await Promise.all([AA.sendMsg(...), BB.sendMsg(...)]);

await is only available if you declare your function as async . await仅在您将 function 声明为async时可用。

Given that, invoking them will give you a promise without extra work.鉴于此,调用它们将为您提供 promise,无需额外工作。

so just do:所以就这样做:

const result = await Promise.all([one(), two()])

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

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