1

I have the following Promise.all example.

Is the promise wrapper necessary with lambda.invoke?

Referenced this thread

function get1(id) {
    return new Promise((resolve, reject) => {
        const params = {
            FunctionName: 'myLambda', // the lambda function we are going to invoke
            InvocationType: 'RequestResponse',
            Payload: { id },
        };

        lambda.invoke(params, (err, data) => {
            if (err) {
                reject(new Error('error'));
            } else {
                const result = JSON.parse(data.Payload);
                resolve(result);
            }
        });
    }).catch(e => Promise.resolve({ error: 'Error has occurred.' }));
}

exports.getDetails = list => Promise.all(list.map(get1))
    .then((response) => {
        return result;
    }).catch((error) => {
        console.log('oops ', error);
    });
Rod
  • 14,529
  • 31
  • 118
  • 230

1 Answers1

6

lambda.invoke() has a callback-signature, which usually means you need to wrap it in a promise, but if you look carefully you'll notice it returns an AWS.Request object, which contains a promise() method. It also documents that

If a callback is not supplied, you must call AWS.Request.send() on the returned request object to initiate the request.

And for AWS.Request.promise():

Sends the request and returns a 'thenable' promise.

So your resulting get1(id) would look like:

function get1(id) {
    const params = {
        FunctionName: 'myLambda', // the lambda function we are going to invoke
        InvocationType: 'RequestResponse',
        Payload: { id },
    };

    return lambda.invoke(params).promise().then(({ Payload }) => JSON.parse(Payload));
}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • where would the error-handling I have in place fit into this? – Rod Aug 18 '18 at 15:21
  • 1
    @Rod the promise is rejected by the API if the request fails, so the `.catch()` in your calling code is sufficient. You shouldn't mask the real error with a `new Error('error')`, which is bad practice since it prevents you from seeing the cause of the issue, so I omitted doing that in my answer. – Patrick Roberts Aug 18 '18 at 15:23
  • How do I add the rejected part? because my catch is not being caught. I can change the error to be more obvious – Rod Aug 18 '18 at 15:45
  • `.catch()` is not invoked unless there's an error. The fact that it's not being called means the code is working. – Patrick Roberts Aug 18 '18 at 15:51
  • How/Where can I add a condition based on the Payload before it returns? – Rod Aug 19 '18 at 03:57
  • Basically, if Payload is empty, I want to reassign or return something else. – Rod Aug 19 '18 at 04:10