Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"Expecting a result, but received an error" when using Promise returned from function #64

Open
paul-uz opened this issue Nov 3, 2020 · 1 comment

Comments

@paul-uz
Copy link

paul-uz commented Nov 3, 2020

I am calling a function which returns a Promise, but it isn't working.

This works:

const self = {
    handler: (event, context, callback) => {
        return Promise.resolve(true).then((response) => {
             callback(null, {success:response})
        });
    }
}

module.exports = self

This doesn't

const self = {
    handler: (event, context, callback) => {
        return self.foo().then((response) => {
            callback('null', {success:response})
        })
    },
    foo: () => {
        return Promise.resolve(true)
    }
}

module.exports = self

My test:

it('Checks foo', () => {
        return lambdaTester(index.handler).event({foo: 'bar'}).expectResult((result) => {
            expect(result.success).to.equal(true)
        })
    })
@richardhyatt
Copy link
Contributor

I think mixing callbacks and promises is not the best thing to do - I would suggest returning a Promise from the handler.

The reason why your second example fails because you're passing a string ('null') instead of null. AWS lambda accepts non-null values as the first parameter of callback() to trigger the error case.

So your first handler (the one that works) would look like:

const self = {
    handler: (event, context, callback) => {
        return Promise.resolve(true).then((response) => {
            return { success: response };
        });
    }
}

module.exports = self

A cleaner way might be:

const self = {
    handler: async (event, context) => {

        // do async stuff here
        const response = await Promise.resolve( true );

        return { success: response };
    }
}

module.exports = self

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants