12

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...

2 Answers 2

27

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

Sign up to request clarification or add additional context in comments.

1 Comment

thank you, a few days after I've opened this question I realized that there is a promise() method on most of the aws-sdk functions, and I have refactored the whole app :)
3

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.