Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return Promise when invoking Lambda function

I'm trying to invoke a Lambda function and return a Promise on finish,

but i get the following error:

"createUser(...).then is not a function"

const createUser = (phone) => {
  return lambda.invoke({
    FunctionName: 'createUser',
    Payload: JSON.stringify({"phone": phone})
  }, (err, data) => {
    let payload = JSON.parse(data.Payload);

    if (payload.statusCode != 200) {
      Promise.reject(payload);
    }
    Promise.resolve(payload);
  })
}

createUser('')
  .then(res => console.log(res))
  .catch(err => console.log(err))

Already tried declaring a new Promise using the

let promise = new Promise((resolve, reject) => {...})

but that didn't work also...

like image 832
Marik Sh Avatar asked Feb 26 '18 07:02

Marik Sh


People also ask

What happens when Lambda is invoked?

With asynchronous invocation, Lambda queues the event for processing and returns a response immediately. For asynchronous invocation, Lambda handles retries and can send invocation records to a destination. To use your function to process data automatically, add one or more triggers.

What should a Lambda return?

The characteristics of lambda functions are: You can use them as an anonymous function inside other functions. The lambda functions do not need a return statement, they always return a single expression.

Can Lambda return data?

Returning a valueIf you use the RequestResponse invocation type, such as Synchronous invocation, AWS Lambda returns the result of the Python function call to the client invoking the Lambda function (in the HTTP response to the invocation request, serialized into JSON).

Can Lambda continue after returning response?

No, this isn't possible.


Video Answer


2 Answers

aws-sdk supports promises through a promise() property on the object returned from most API methods, like so:

const createUser = (phone) => {
    return lambda.invoke({
        FunctionName: 'createUser',
        Payload: JSON.stringify({"phone": phone})
    }).promise();
}

createUser('555...')
.then(res => console.log)
.catch(err => console.log);

https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/using-promises.html

like image 167
tomsun Avatar answered Sep 28 '22 14:09

tomsun


Alright,figured it out...

I haven't returned the promise correctly.

to fix the error, I have declared the lambda.invoke inside of a new Promise, and then returned the Promise like this:

const createUser = (phone) => {
   let promise = new Promise((resolve, reject) => {
    lambda.invoke({
      FunctionName: 'createUser',
      Payload: JSON.stringify({"phone": phone})
    }, (err, data) => {
      let payload = JSON.parse(data.Payload);
      if (payload.statusCode != 200) {
        reject(payload);
      } else {
        resolve(payload);
      }
    })
  })
  return promise;
}
like image 38
Marik Sh Avatar answered Sep 28 '22 16:09

Marik Sh