0

I'm a bit confused about this design. What is the proper way to use async/await? Here's a basic situation I'm dealing with:

I'm a client app using a REST API. I have a function like this:

//Class method to get user list.
async getUsers(url) {
    let options = {
        method: 'GET',
        uri: url,
        json: true,
        headers: {
            Authorization: this.authString
        }
    }

    //Using request-promise module.
    let users = await request(options)
    return users
}

This method gets a list of users, then because the method is async, it returns the list in a promise. So basically, I'm getting the resolved value from the promise using 'await', but then it gets wrapped in another promise when I call getUsers(). I want to be able to return the user list and not a promise, but if I remove async keyword, I can't call await. What is the best approach for this kind of problem?

u84six
  • 4,604
  • 6
  • 38
  • 65
  • 2
    That's what the `async` keyword is for. It declares that the function returns a Promise and enables the use of `await` inside it. – Paul Oct 30 '18 at 14:31
  • 3
    The title of this question is a true statement. – Pointy Oct 30 '18 at 14:31
  • *"I want to be able to return the user list and not a promise"* You can't. See the linked question's answers for why. Whatever calls `getUsers` *also* has to handle the asynchronous nature of what you're doing (and its caller does, etc., right the way up the chain). – T.J. Crowder Oct 30 '18 at 14:34
  • So in this case, it doesn't really make sense to use await. Might as well just return the original promise, correct? Or I suppose I could use a callback (which kind of defeats the purpose of await). – u84six Oct 30 '18 at 14:40
  • 2
    Yeah, may as well return the original Promise in this case: `return request(options);`. – Paul Oct 30 '18 at 14:47

0 Answers0