A hanging Promise was canceled

ExpertTip
#1

Hi, I’m trying to use Cloudflare Workers to send a message to Amazon SQS. I’m using @aws-sdk/client-sqs-node with Webpack but I’m getting the following error:

A hanging Promise was canceled. This happens when the worker runtime is waiting for a Promise from JavaScript to resolve, but has detected that the Promise cannot possibly ever resolve because all code and events related to the Promise's request context have already finished.
Uncaught (in response) Error: The script will never generate a response.

This is my script:

const {
    SQSClient
} = require('@aws-sdk/client-sqs-node/SQSClient');
const {
    SendMessageCommand
} = require('@aws-sdk/client-sqs-node/commands/SendMessageCommand');

global.location = {
    protocol: "https:"
};

const sqs = new SQSClient({
    credentials: {
        accessKeyId: '<ACCESS_KEY>',
        secretAccessKey: '<SECRET>'
    },
    region: 'eu-west-3'
});

addEventListener('fetch', function (event) {
    event.respondWith(handleRequest(event.request));
});

async function handleRequest(req) {
    console.log('Got request', req);
    try {
        await sqs.send(new SendMessageCommand({
            MessageBody: "test message",
            QueueUrl: "<SQS_URL>"
        }));
        return new Response('OK', {
            status: 200
        });
    } catch (err) {
        return new Response("KO", {
            status: 500
        });
    }
}

My Webpack config:

module.exports = {
    entry: './src/main.js',
    mode: 'development',
    optimization: {
        minimize: false
    },
    output: {
        path: __dirname + "/dist",
        publicPath: "dist",
        filename: "worker.js"
    },
    target: 'webworker',
    node: {
        fs: 'empty'
    }
}

The compiled worker script works perfectly when executed as a service worker directly from the browser.

0 Likes

#3

Instead of using AWS’s library you might consider mhart’s aws4fetch library which is much lighter and designed to work within the Service Worker environment.

It’s compatible with AWS Signature Version 4 process and I’ve used it for both SQS and S3. Here is an example which signs requests to SQS in a Service Worker: https://github.com/obezuk/cf-worker-aws-fetch/tree/sqs

1 Like