0

There is a list of unlimited cars in backend. Each car has an id (unique id) and a name (car model name).

I have the list of car IDs, example:

const carIds = ['abc','xyz'];

and I need to fetch respective car names for the above car Ids. I tried the below code, but its not working at all, what is that I'm missing ?

const carIds = ['abc','xyz']; // unique ids
const carsList = [];
for (const carId of carIds) {
  this.api.getCar(carId).pipe(
    map(response => {
      carsList.push({
        name: response.name,
        id: carId
      });
    })
  );
}
console.log(carsList); // When I run this, its printing nothing.

Expected Output:

carsList = [{
 id: 'abc',
 name: 'benz'
},{
 id: 'xyz',
 name: 'mercede'
}]

Thanks in advance.

1
  • Use Promise.all([ promise1, promise2 ]) to run 2 promises at the same time. Commented Jun 2, 2020 at 17:34

2 Answers 2

2

You can use forkJoin to subscribe to many streams by once and get the result when all stream are complete, it is like a promise.all for rxjs.

const carIds = ['abc','xyz']; // unique ids
const httpCalls = carIds.map(id => this.api.getCar(id)) // array of streams
const carsList$ = forkJoin(httpCalls).pipe(
   map(results => results.map((r, index) => ({ id: carIds[index], name: r.name }));
);

carsList$.subscribe(console.log);
Sign up to request clarification or add additional context in comments.

Comments

0
const carsList = [];

for await (const carId of carIds) {
  const car = await this.api.getCar(carId);
  car && carsList.push({
        name: car.name,
        id: carId
      });
}

Try this code. Happy to help :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.