0
export function getHotOffers() {
    let offers;
    getRequest('/hot-offers').then(x => offers = x);
    alert(offers);
    return JSON.parse(offers);
}

That's my function I export. It makes request to the server asynchronously and get JSON string. When I debug the project, everything works and alert returns string but when I just execute the code, alert returns undefined. How can I fix this?

3 Answers3

3

This isn't how promises work. The code after getRequest() doesn't wait for the promise to complete - it just runs straight away.

export function getHotOffers() {
    let offers;
    getRequest('/hot-offers').then( x =>
       //this only happens after the request is done
       offers = x 
    );
    //this code runs right away, before the request completes
    alert(offers);
    //so does this, so "offers" will be undefined at this point
    return JSON.parse(offers);
}

All the code to run after the request returns should be inside your call back, like this:

export function getHotOffers() {
    return getRequest('/hot-offers');
}

//somewhere else
getHotOffers().then( offers => {
   useTheOffers( offers );
});
Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20
1

The data is not synchronously available. You will need to use the promise to get access to the offers.

export function getHotOffers() {
    let offerPromise = getRequest('/hot-offers')
        .then(offers => JSON.parse(offers));
    return offerPromise;
}

Similarly, any code that calls this will be getting a promise and will have to use its .then method to get the final value.

getHotOffers().then(offers => {
    alert(offers);
});
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
1

Your code proceeds before the callback passed to then is called.

Using async/await, you can circumvent this, and improve legibility of your code:

// emulate your "getRequest" function which returns a promise:
async function getRequest(path) {
    await new Promise(resolve => setTimeout(resolve, 500)); // simulate response delay
    const offers = ['hot-offer-1', 'hot-offer-2', 'hot-offer-3'];
    return offers;
}

async function getHotOffers() {
    const offers = await getRequest('/hot-offers');
    console.log(offers);
    return JSON.parse(offers);
}

getHotOffers();
ideaboxer
  • 3,863
  • 8
  • 43
  • 62