Обработка объекта ответа от каждого обещания в Promise.all () - PullRequest
0 голосов
/ 25 октября 2018

У меня есть конечная точка публикации, которая создает клиентов и возвращает userId в качестве ответа

Например

// Post Data
const customers = [{
    firstName: 'John',
    lastName: 'Smith',
    userId: '12345
  },
  {
    firstName: 'Phil',
    lastName: 'Doe',
  },
  {
    firstName: 'Dan',
    lastName: 'Joe',
  }
]


app.post('/customers', (req, res) => {
  const arrayPromises = []
  const customers = req.body.customers;
  customers.forEach((customer) => {
    //checking whether I have a userId already
    if (!customer.userId) {
      const postRequest = {
        headers: Object.assign(res._headers, {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        }),
        post:'www.createUserExample.com,
        customer // post data,
      };
      arrayPromises.push(axios(postRequest))
      //response will be {userId}
    }
  })


  Promise.all(arrayPromises).then(result => {
    //by this way I get all userids
    res.status(200).json(result.data)
  })


})

Но мне нужно отправить объект ответа обратно с включением userIds

пример объекта ответа должен быть похож на

[{
    firstName: 'John',
    lastName: 'Smith',
    userId: '12345'
  },
  {
    firstName: 'Phil',
    lastName: 'Doe',
    userId: '65765'
  },
  {
    firstName: 'Dan',
    lastName: 'Joe',
    userId: '786876'
  }
]

Итак, в общем, я хотел бы иметь свойства клиентов и добавить созданный userId для публикации объекта данных и отправки в качестве ответа.

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

Ответы [ 3 ]

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

Просто поместите объекты, которые уже имеют идентификатор, в массив.(Или обещания для них).Promise.all приведет к массиву, который вы ищете.Массив не обязательно должен содержать только обещания для запросов API:

const arrayPromises = []
const customers = req.body.customers;
customers.forEach((customer) => {
  //checking whether I have a userId already
  if (customer.userId) {
    arrayPromises.push(Promise.resolve(customer));
  } else {
    arrayPromises.push(axios(…));
  }
});

Вы также можете упростить до

const arrayPromises = req.body.customers.map((customer) => {
  //checking whether I have a userId already
  return customer.userId
    ? Promise.resolve(customer)
    : axios(…);
});
0 голосов
/ 25 октября 2018

Вы можете сопоставить customers, возвращая те, у которых уже есть userId, и отправлять запросы на запросы тех, у кого их нет.

const promises = customers.map(async (customer) => {
    //checking whether I have a userId already
    if (customer.userId) {
        return customer;
    }

    const {userId} = await axios({
        headers: Object.assign(res._headers, {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        }),
        post: 'www.createUserExample.com',
        customer // post data,
    });
    return {userId, ...customer};
});
0 голосов
/ 25 октября 2018

Сначала вам нужно отфильтровать пользователей без идентификаторов:

const idLess = customers.filter(customer => !customer.userId);

Затем вы делаете запросы на idLess вместо customers.

const arrayPromises = idLess.map(customer => {
    const postRequest = {
        headers: Object.assign(res._headers, {
           Accept: 'application/json',
           'Content-Type': 'application/json',
        }),
        post:'www.createUserExample.com,
        customer // post data,
    };

    // if your service responds with the entire obj:
    return axios(postRequest);

    // if your service responds just with ids:
    return axios(postRequest).then(id => Object.assign({
       userId: id
    }, customer))l
});

Теперь вам нужнофильтр для пользователей с идентификаторами:

const idd = customers.filter(customer => customer.userId);

Затем вы присоединяете свои массивы.

Promise.all(arrayPromises).then(result => {
   // either with concat
   res.status(200).json(result.data.concat(idd));

   // or by destructuring
   res.status(200).json([...result.data, ...idd]);
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...