Home > database >  Why promise.all crash an error but not sending promises one by one?
Why promise.all crash an error but not sending promises one by one?

Time:03-29

I'm pretty new here and I have a problem on my backend nodejs.

I have a list of object that will help me find a car in the database, and so I prepare promises to get data one by one and send that inside a promise.all to trigger the promises.

the function getCar is working every time with data I sent but When I do the promise.all with the array then it will have an error of pool of connection. What is the probleme ?

function requestData (listOfCar) {
    const promiseList = [];

    for (let i = 0; i < listOfCar.length; i  ) {
        promiseList.push(getCar(listOfCar[i]));
    }

    return Promise.all(promiseList); // crash but sending promises one by one is working
}

function getCar(carFinder) {
    // do things and return a query find in sequelize to find a car 
    // and so it return a promise
}```

CodePudding user response:

Promise are always directly trigger, they do not wait to be trigger inside the promise.all. So your problem is that you are sending I guess way to many request inside the database and so the pool of connection do not accept it anymore To fix that you can add more pool of connection or you can simply trigger promise little chunk of 5 and await the promise.all

async function requestData (listOfCar) {
    const carLists = [];

    for (let i = 0; i < listOfCar.length; i  ) {
        const tmpListOfPromise = [];
        for (let j = 0; j < 5 && i < listOfCar; j  ) {
            const tmpListOfPromise.push(getCar(listOfCar[i]));
            i = i   1;
        }
        await Promise.all(tmpListOfPromise).then((response) => {
            carLists = carLists.concat(response);  // this will push every response in the list
        });
    }
}

function getCar(carFinder) {
    // do things and return a query find in sequelize to find a car
    // and so it return a promise
}
  • Related