简体   繁体   English

处理被拒绝的承诺而不用混乱的 try catch

[英]Dealing with rejected promises without messy try catch

I have a simple function, which looks similar to the following我有一个简单的 function,看起来类似于以下

const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

}

apiRequest returns a number. apiRequest 返回一个数字。

This function is surrounded by a function which handles errors for many functions.这个 function 被 function 包围,它处理许多功能的错误。

However for this specific function, I don't just want to return an error to the user in the case of one of the apiRequests failing in the second part of the ternary.但是对于这个特定的 function,我不只是想在三元组的第二部分中的一个 apiRequests 失败的情况下向用户返回错误。

const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

// intended logic for second part of ternary
if apiRequest and apiRequest resolve, return apiRequest + apiRequest2
if apiRequest fails, return apiRequest2
if apiRequest 2 fails, return apiRequest
}

I'm not exactly sure of the way I should be going about this.我不确定我应该怎么做。 Perhaps I could surround each part with try and catch, and in the catch statement I could then try the next part of the logic?也许我可以用 try 和 catch 包围每个部分,然后在 catch 语句中我可以尝试逻辑的下一部分?

I feel like I will end up with a super messy function in this case在这种情况下,我觉得我最终会得到一个超级凌乱的 function

First of all, await needs to occur in an async function, so the code in your question cannot run.首先, await需要发生在async function 中,因此您问题中的代码无法运行。

If I understand correctly, you still want the function to return a rejected promise when both promises reject.如果我理解正确,您仍然希望 function 在两个承诺都拒绝时返回被拒绝的 promise。

You could define a utility function that takes an array as promises and returns a single promise that only rejects when all given promises reject (with the reason of the rejection of the first promise).您可以定义一个实用程序 function ,它将数组作为承诺并返回单个 promise ,仅当所有给定的承诺都拒绝时才会拒绝(原因是第一个承诺被拒绝)。 In all other cases it will resolve to an array with the individual fulfilled values, or with the default value when the corresponding promise rejected.在所有其他情况下,它将解析为具有单个已实现值的数组,或者当相应的 promise 被拒绝时使用默认值。

This utility function could look like this:此实用程序 function 可能如下所示:

async function fulfilled(promises, defValue) {
    const res = await Promise.allSettled(promises);
    if (res.every(p => p.status == "rejected")) throw res[0].reason;
    return res.map(p => p.status == "fulfilled" ? p.value : defValue);
}

Then your function could look like this:那么您的 function 可能如下所示:

const foo = async (bar) => {
    return ![val1, val2].includes(bar) ? apiRequest :
        (await fulfilled([apiRequest, apiRequest2], 0)).reduce((a, b) => a + b);
}

You can try this你可以试试这个

  defaultval="no value"
    const foo = async (bar,apiCalls,defaultval) => {
        var finalresult= await Promise.allSettled(apiCalls)
    .then(resp=>resp.map(p=>p.status==='fulfilled'?p.value:defaultval))
    .then((res)=>{
        var finalnumber=res.filter(x=>x!='no value')
        return finalnumber.length==0?defaultval:finalnumber.reduce((a, b) => a + b)
    })
        return  ![val1, val2].includes(bar) ? apiRequest : finalresult
    }

as answered by @trincol if one of the two promises fail it will add the reminder to the default value, if all promises fail it will throw an error and won't return a value, it won't return a default value.正如@trincol 所回答的那样,如果两个承诺之一失败,它会将提醒添加到默认值,如果所有承诺都失败,它将抛出错误并且不会返回值,也不会返回默认值。 So I adjusted the code like this所以我调整了这样的代码

defaultval="no value"

async function fulfilled(apiCalls,defaultval) {
    const res = await Promise.allSettled(apiCalls);
    return res.map(p => p.status == "fulfilled" ? p.value:defaultval)
}

const foo = async (bar,defaultval) => {
   var result= await fulfilled([apiRequest, apiRequest2])
   var numb=result.filter(x=>x!=defaultval)
   return ![val1, val2].includes(bar) ? apiRequest :(numb.length==0?defaultval:numb.reduce((a, b) => a + b)
   )
}

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

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