Настройте отклоненный ответ в Promise.all () - PullRequest
0 голосов
/ 26 октября 2018

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

Я сослался на Обработка ошибок в 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.log(arrayOfPromises)
  } catch (err) {
    console.log(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

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

Ответы [ 2 ]

0 голосов
/ 26 октября 2018

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

Функция 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
  }
}));
0 голосов
/ 26 октября 2018

Используйте перехват вместо того, чтобы после вызова 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.log(arrayOfPromises)
  } catch (err) {
    console.log(err)
  }
}

mainFunction();

Надеюсь, это поможет:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...