logo

How to Wait for API Responses Asynchronously

When your application calls a slow external API — payment processing, AI inference, video conversion — you have two choices: block your server while waiting, or offload the work to a task queue.

This guide shows you how to use AsyncQueue to fire-and-forget API calls and retrieve the result when it’s ready.

The Problem

// This blocks your server for 30+ seconds
app.post('/convert-video', async (req, res) => {
const result = await fetch('https://slow-api.example.com/convert', {
method: 'POST',
body: JSON.stringify({ videoUrl: req.body.url }),
});
const data = await result.json();
res.json(data); // User waited 30 seconds for this
});

On serverless platforms, the function might timeout before the response even arrives.

The Solution: Offload to AsyncQueue

Step 1: Create an AsyncQueue account and get your API key

Sign up at asyncqueue.io and generate an API key from the dashboard. Store it as an environment variable.

Terminal window
ASYNCQUEUE_API_KEY=your_api_key_here

Step 2: Install the AsyncQueue SDK

Terminal window
# Node.js
npm install asyncqueue-js
# Python
pip install asyncqueue-python

Step 3: Create a task with a callback URL

Instead of calling the slow API directly, create an AsyncQueue task that handles the call:

import { AsyncQueue } from 'asyncqueue-js';
const aq = new AsyncQueue({ apiKey: process.env.ASYNCQUEUE_API_KEY });
app.post('/convert-video', async (req, res) => {
const task = await aq.tasks.create({
targetUrl: 'https://slow-api.example.com/convert',
payload: { videoUrl: req.body.url },
retries: 3,
webhookUrl: 'https://your-app.com/api/on-convert-complete',
});
// Respond immediately with the task ID
res.json({ taskId: task.id, status: 'processing' });
});

Your endpoint now responds in milliseconds rather than 30+ seconds.

Step 4: Handle the callback response

Create an endpoint that AsyncQueue calls via webhook when the external API finishes:

app.post('/api/on-convert-complete', async (req, res) => {
const { taskId, result, status } = req.body;
// Save the result, notify the user, update the UI
await saveConversionResult(taskId, result);
await notifyUser(taskId, 'Your video is ready!');
res.json({ received: true });
});

Step 5: Query the task result via API

You can also check task status programmatically:

const task = await aq.tasks.get('task_abc123');
console.log(task.status); // 'completed'
console.log(task.result); // { convertedUrl: 'https://...' }

The AsyncQueue dashboard also provides a visual overview of all your tasks.

When to Use This Pattern

  • Payment processing: Charge a card and wait for confirmation
  • AI/ML inference: Send data to an AI model and get results later
  • File processing: Convert, compress, or analyze uploaded files
  • Third-party integrations: Sync data with slow external services
  • Email delivery: Send emails through providers with slow APIs