Настроить отклоненный ответ в Promise.all ()

Привет, я пытаюсь настроить ответ на ошибку, если обещание из массива не выполняется

Я сослался на Обработка ошибок в 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

Пожалуйста, дайте мне знать, смогу ли я получить результат, как указано выше

Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
43
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Используйте уловку вместо 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
  }
}));

Другие вопросы по теме