Rod
Rod

Reputation: 15455

Is promise wrapper necessary around lambda.invoke?

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

Upvotes: 1

Views: 1182

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51896

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

Upvotes: 6

Related Questions