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...
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.
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.
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).
No, this isn't possible.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With