#javascript #typescript #asynchronous #async-await
#javascript #машинописный текст #асинхронный #асинхронное ожидание
Вопрос:
Я бы хотел выполнить параллельно два вызова API внутри моего thunk. Тем не менее, мне нужно правильно обрабатывать ошибки. Я подготовил упрощенную версию своих асинхронных функций. Разделы, которые я хочу распараллелить, прокомментированы.
async function addCredentialA() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.5)
return resolve({status: '200'})
else
return reject({status: '500'})
}, 1000)
});
}
async function addCredentialB() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.3)
return resolve({status: '200'})
else
return reject({status: '500'})
}, 2000)
});
}
async function addCredentials(sendRequestA: boolean, sendRequestB: boolean) {
try {
// This should be parallel
if (sendRequestA) {
try {
await addCredentialA()
console.log('Successfully added credential A')
} catch (e) {
console.log('Something wrong with credential A', e)
throw e
}
}
// This should be parallel
if (sendRequestB) {
try {
await addCredentialB()
console.log('Successfully added credential B')
} catch (e) {
console.log('Something wrong with credential B', e)
throw e
}
}
console.log('Succesfully added two credentials')
} catch (e) {
console.log('There was problem with adding credentials')
console.log(e)
}
}
addCredentials(true, true)
Мне удалось распараллелить эти два вызова , обернув их в функции и вызвав их с Promise.all
помощью .
async function addCredentials(sendRequestA: boolean, sendRequestB: boolean) {
const requestACall = async () => {
if (sendRequestA) {
try {
await addCredentialA()
console.log('Successfully added credential A')
} catch (e) {
console.log('Something wrong with credential A', e)
throw e
}
}
}
const requestBCall = async () => {
if (sendRequestB) {
try {
await addCredentialB()
console.log('Successfully added credential B')
} catch (e) {
console.log('Something wrong with credential B', e)
throw e
}
}
}
try {
await Promise.all([requestACall(), requestBCall()])
console.log('Succesfully added two credentials')
} catch (e) {
console.log('There was problem with adding credentials')
console.log(e)
}
}
Но есть ли лучший вариант? Типографская игровая площадка