0

so I have a function (getBagId) that I want to return the bag id, I know its not returning it due to the async nature, but how would i go about fixing it so it returns the bagId, heres the code

const getBagId = () => {
    request.get('https://www.off---white.com/en-us/api/users/me', options, (err, res, data) => {
        bagId = data.bagId

    })
    return bagId
}

once again I want the function to return bagId so the value is set to that, also i want to do this only using callbacks, no promises or async await, thanks

Kendall Kelly
  • 121
  • 1
  • 10
  • If you want to understand async behavior in JavaScript, this is a great place to start: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises – Cat Feb 04 '20 at 18:50
  • thanks, i understand it, just wondering how i would go about fixing that – Kendall Kelly Feb 04 '20 at 18:51

3 Answers3

0

Use request-promise

const getBagId = async () => {

    const response = await rp({ uri : 'https://www.off---white.com/en-us/api/users/me' })

    // Process the `bagId` from the response (JSON / XML / ??? )
    const bagId = // `bagId` from response.

    return bagId
}

Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44
0

You could make use of promises:

const getBagId = () => {
    return new Promise((res, rej) => {
        request.get('https://www.off---white.com/en-us/api/users/me', options, (err, res, data) => {
            if(err) return rej(err);
            return res(data.bagId);
        });
    });
}

But now your .getBagId() returns a promise, so you'll have to handle it accordingly in your application

guijob
  • 4,413
  • 3
  • 20
  • 39
0

request.get is an asynchronous function, so getById needs to return a promise or to execute asynchronously by using async/await. Otherwise you cannot do it unless there is some version of request.get method that execute synchronously, which I highly doubt that it exists.

ahmad
  • 56
  • 1
  • 4