Привет, я пытаюсь настроить ответ на ошибку, если обещание из массива не выполняется
Я сослался на Обработка ошибок в Promise.all и разработал приведенный ниже код Мне может потребоваться настроить его, чтобы получить желаемый ответ. Нужна помощь
Я реализовал следующий код. Пожалуйста, бегите, чтобы увидеть выход
//User Data
const usersData = [{
firstName: 'John',
lastName: 'Smith',
isResolved: true //I have this only to reject or resolve the promise
},
{
firstName: 'Phil',
lastName: 'Doe',
isResolved: false
},
{
firstName: 'Dan',
lastName: 'Joe',
isResolved: true
}
]
//Promise which gets resolved
const delayResolveFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const id = Math.floor((Math.random() * 10) + 1)
resolve({
userid: id,
isSuccess: true
})
}, 100)
})
}
// Promise which gets rejected
const delayRejectFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const id = Math.floor((Math.random() * 10) + 1)
reject({
isSuccess: false
})
}, 100)
})
}
//function which creates users based on whethere userid is present
const createUsers = (users) => {
const promiseArray = [];
users.forEach((user) => {
let userId = user.id;
if (!userId) {
if (user.isResolved) {
promiseArray.push(delayResolveFunction().then((response) => {
userId = response.userid
isSuccess = response.isSuccess
return { ...user,
userId,
isSuccess
}
}))
}
if (!user.isResolved) {
// statement is not executed because error is thrown
promiseArray.push(delayRejectFunction().then((response) => {
userId = response.userId
return { ...user,
userId
}
}))
}
} else return null;
});
// I have this logic to access the data even if one promise fails among three
//If you look at the response object we can see request for second user failed
// My question is can I also send user object for failed response?
return Promise.all(promiseArray.map(p => p.catch((err) => {
return err;
})))
}
//mainfunction where array of promises are resolved
const mainFunction = async() => {
try {
const arrayOfPromises = await createUsers(usersData);
console.info(arrayOfPromises)
} catch (err) {
console.info(err)
}
}
mainFunction();
Я хочу получить результат, как показано ниже
[{
"firstName": "John",
"lastName": "Smith",
"isResolved": true,
"userId": 3,
"isSuccess": true
},
{
//for failed response
"firstName": 'Phil',
"lastName": 'Doe',
"isResolved": false,
"isSuccess": false
},
{
"firstName": "Dan",
"lastName": "Joe",
"isResolved": true,
"userId": 8,
"isSuccess": true
}
]
если вы хотите посмотреть код, вот ссылка https://codepen.io/punith77/pen/OBdLZa?editors=0012
Пожалуйста, дайте мне знать, смогу ли я получить результат, как указано выше
Используйте уловку вместо then после вызова delayRejectFunction
. И используйте объект ошибки в catch, чтобы получить isSuccess
. Я опубликовал изменения ниже.
//User Data
const usersData = [{
firstName: 'John',
lastName: 'Smith',
isResolved: true //I have this only to reject or resolve the promise
},
{
firstName: 'Phil',
lastName: 'Doe',
isResolved: false
},
{
firstName: 'Dan',
lastName: 'Joe',
isResolved: true
}
]
//Promise which gets resolved
const delayResolveFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const id = Math.floor((Math.random() * 10) + 1)
resolve({
userid: id,
isSuccess: true
})
}, 100)
})
}
// Promise which gets rejected
const delayRejectFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject({
isSuccess: false
})
}, 100)
})
}
//function which creates users based on whethere userid is present
const createUsers = (users) => {
const promiseArray = [];
users.forEach((user) => {
let userId = user.id;
if (!userId) {
if (user.isResolved) {
promiseArray.push(delayResolveFunction().then((response) => {
userId = response.userid
isSuccess = response.isSuccess
return { ...user,
userId,
isSuccess
}
}))
}
if (!user.isResolved) {
// statement is not executed because error is thrown
promiseArray.push(delayRejectFunction().catch((errorObj) => {
var isSuccess = errorObj.isSuccess;
return { ...user,
isSuccess
}
}))
}
} else return null;
});
// I have this logic to access the data even if one promise fails among three
//If you look at the response object we can see request for second user failed
// My question is can I also send user object for failed response?
return Promise.all(promiseArray.map(p => p.catch((err) => {
return err;
})))
}
//mainfunction where array of promises are resolved
const mainFunction = async() => {
try {
const arrayOfPromises = await createUsers(usersData);
console.info(arrayOfPromises)
} catch (err) {
console.info(err)
}
}
mainFunction();
Надеюсь это поможет :)
Я не совсем уверен, где этот код будет использоваться в вашей базе кода, но вы можете внести эти изменения
Функция delayRejectFunction
// Promise which gets rejected
const delayRejectFunction = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
const id = Math.floor((Math.random() * 10) + 1)
reject({
userid: id,
isSuccess: false
})
}, 100)
})
}
Вызов функции delayRejectFunction
// statement is not executed because error is thrown
promiseArray.push(delayRejectFunction().then((response) => {
userId = response.userId
return { ...user,
userId
}
}).catch(err => {
userId = err.userid
isSuccess = err.isSuccess
return { ...user,
userId,
isSuccess
}
}));