Help with variables based on API call

Can anyone help me with the following?

I have an API with a operation "OrdersCount" to get back the total amount of orders within the webshop. I get back a number, p.e. 2347. I want to use this result to know how many pages I have to loop through to get all of the order records.

// So therefore I had 4 variables in mind to use as input for the for-loop:

//first - this is the OrdersCount query - totalOrders is a Promise
const totalOrders = Promise.resolve(OrdersCount.trigger({additionalScope: {createdAtMin}}));

//second - total records per page
const pageLimit = 50;

//third - the start pagenumber
let page = 1;

//fourth - the calculated number of pages i have to loop through
let totalPages = Math.ceil(totalOrders / pageLimit);


for (page; page <= totalPages; page++) {
    console.log('This is page '+ page + ' of total ' + totalPages);  // This console.log shows nothing!!!!
}

return totalOrders;

It looks like that I'm not able to use my totalOrders in my calculation of totalPages. How can I solve this situation? Please help me!

I might try to put the rest of that code in onSuccess of the first query, like this?

// So therefore I had 4 variables in mind to use as input for the for-loop:

//first - this is the OrdersCount query - totalOrders is a Promise
return OrdersCount.trigger({
    additionalScope: { createdAtMin },
    onSuccess: totalOrders => {
        //second - total records per page
        const pageLimit = 50;

        //third - the start pagenumber
        let page = 1;

        //fourth - the calculated number of pages i have to loop through
        let totalPages = Math.ceil(totalOrders / pageLimit);

        for (page; page <= totalPages; page++) {
            console.log('This is page ' + page + ' of total ' + totalPages);  // This console.log shows nothing!!!!
        }

        return totalOrders;
    }
});

Thanks @khill-fbmc for the reply.

The problem stays!

If I look into the console.log the value of totalPages is NaN. I suppose that this occurs because the result of the totalOrders is a Promise and not a Number.

Do you know how to cast a Promise into a Number? Or do you have a better solution for this?

can you log totalOrders? is the OrdersCount completing?

what if you try instead of a param here... onSuccess: totalOrders => {

try doing this?

onSuccess: () => {
    // ...
    let totalPages = Math.ceil(Number(OrdersCount.data) / pageLimit);
    // ...
}

Another thing to try is just awaiting the initial promise

await OrdersCount.trigger();

const totalCount = Number(OrdersCount.data);
1 Like

Thanks @khill-fbmc This is the solution!!

1 Like