0

I am trying to use Nodejs, express, axios. In my controller I have this function getStoresNearAddress which uses 2 axios promises [requestStore, requestInfo]. a piece of data from requestStore is needed to be used in requestInfo. I used a global variable storeId for this purpose. No matter what I do, it won't work. It works if each promise was used independently.

var storeId; //  <---
const API_URL = "https://order.dominos.com/power";
const orderTypes = {
    Delivery: "Delivery",
    Carryout: "Carryout",
};
const homeRegion = "city, state, zip";
const homeAddress = "555 main Rd";

const urlStore = `${API_URL}/store-locator?type=${orderTypes.Carryout}&c=${homeRegion}&s=${homeAddress}`;
const urlInfo = `${API_URL}/store/${storeId}/profile`;
//
const requestStore = axios.get(urlStore);
const requestInfo = axios.get(urlInfo);

getStoresNearAddress = (req, res) => {
    Promise.all([requestStore, requestInfo])
        .then((responses) => {
            storeId = responses[0].data.Stores.find((store) => store.IsDeliveryStore).StoreID; //  <----
            res.send(responses[1].data);
            console.log(responses[1].data);
        })
        .catch((error) => {
            console.log(error);
        });
};

I just don't know how to do it this, I guess too new to all these. I tried a lot to find some references. I found one, but too abstract to comprehend. I know I can't do it this way by simultaneous call like I used it here in Promise.all. Can you please advise with correction / suggestion on my code?

  • 1
    That code **will** assign to `storeId`, if you ever call `getStoresNearAddress`, **if** both of those promises are fulfilled. But assigning to something you're closing over like that is usually an antipattern; instead, use the information you receive in the `then` callback or return the promise chain from ``getStoresNearAddress` and return the information that callers of that function will need from the fulfillment handler. – T.J. Crowder Jan 02 '21 at 16:34
  • "*I know I can't do it this way by simultaneous call*" - so, did you try chaining? – Bergi Jan 02 '21 at 16:46
  • Where are you actually trying to use the `storeId` result? We need to see that code as that determines what solution would work best. FYI, I agree with T.J. that assigning to a higher scoped variable like `storeId` from within an asynchronous handler is an anti-pattern 99% of the time. It's usually a sign that the asynchronous code is not properly written and will either suffer from timing problems or concurrency problems or both. – jfriend00 Jan 02 '21 at 16:48

0 Answers0