Reputation: 731
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...
Upvotes: 12
Views: 10514
Reputation: 286
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
Upvotes: 27
Reputation: 731
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;
}
Upvotes: 3