Vikram Khemlani
Vikram Khemlani

Reputation: 635

How to res.send something in loopback-next

I have a function that has a callback as shown below, and I want to return account that is returned in the callback as a response to the request for the function. How could I res.send the account (since I cannot return values from a callback function)

@get('/payments/retrieve-stripe/{id}', {
    responses: {
      '200': {
        description: 'User model instance',
        content: {'application/json': {schema: {'x-ts-type': User}}},
      },
    },
  })
  async retrieveStripe(@param.path.number('id') id: number,
  @requestBody() req: any): Promise<any> {
    if (!req.stripeAccountId) {
      throw new HttpErrors.NotFound('No Stripe Account');
    }
    else {
    stripe.accounts.retrieve(
  req.stripeAccountId,
  async function(err: any, account: any) {
    //console.log(err)
   console.log(account)
    return account
  })
    }
  }

Upvotes: 0

Views: 100

Answers (1)

Marvin Irwin
Marvin Irwin

Reputation: 1010

If you're stuck using a callback any any point in your code you're going to use manual promises (or maybe some promise wrapping library).

Instead of using async and return, use resolve() which functionally can return from any point in your function, regardless of scope.

@get('/payments/retrieve-stripe/{id}', {
    responses: {
      '200': {
        description: 'User model instance',
        content: {'application/json': {schema: {'x-ts-type': User}}},
      },
    },
  })
  retrieveStripe(@param.path.number('id') id: number, @requestBody() req: any): Promise<any> {
    return new Promise((resolve, reject) => {
      if (!req.stripeAccountId) {
        throw new HttpErrors.NotFound('No Stripe Account');
      }
      else {
        stripe.accounts.retrieve(req.stripeAccountId, function(err: any, account: any) {
          resolve(account);
        })
      }
    });
  }

Upvotes: 1

Related Questions