You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Ajax依次发送数组元素?需待前请求完成(附异步疑问)

How to Send Ajax Requests Sequentially (One After Another)

Great question—you’re absolutely right that Ajax is asynchronous by default, meaning your script doesn’t pause to wait for a server response before moving on. But that doesn’t mean we can’t force requests to run one after another. Let’s break down how to do this properly.

Understanding the Core Idea

Ajax’s asynchronous nature just means the browser doesn’t block the entire page while waiting for a response. We can still control the execution flow using modern JavaScript features like Promises or async/await to make each request wait for the previous one to finish.

Method 1: Promise Chaining with reduce

We can wrap each Ajax request in a Promise, then use Array.reduce() to chain them together—ensuring each request only starts after the prior one resolves.

Here’s a practical example using the Fetch API (you can adapt this to XMLHttpRequest if needed):

const items = ['This', 'is', 'a', 'fake', 'array'];

// Wrap your Ajax request in a reusable Promise function
function sendItem(item) {
  return fetch('/your-api-endpoint', {
    method: 'POST',
    body: JSON.stringify({ item: item }),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => {
    if (!response.ok) throw new Error(`Request failed: ${response.status}`);
    return response.json(); // Process the response as needed
  })
  .then(data => {
    console.log(`Successfully sent "${item}":`, data);
    return data; // Pass results to the next chain step
  })
  .catch(error => {
    console.error(`Failed to send "${item}":`, error);
    throw error; // Optional: Stop subsequent requests on failure
  });
}

// Chain all requests sequentially with reduce
items.reduce((previousRequest, currentItem) => {
  return previousRequest.then(() => sendItem(currentItem));
}, Promise.resolve()); // Start with a resolved Promise to kick off the chain

Method 2: Async/Await with a Loop

For cleaner, more readable code, use async/await with a for...of loop. This makes asynchronous code look almost like synchronous code, making the sequential flow obvious.

const items = ['This', 'is', 'a', 'fake', 'array'];

async function sendItemsSequentially() {
  for (const item of items) {
    try {
      const response = await fetch('/your-api-endpoint', {
        method: 'POST',
        body: JSON.stringify({ item: item }),
        headers: {
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) throw new Error(`Request failed: ${response.status}`);
      
      const data = await response.json();
      console.log(`Successfully sent "${item}":`, data);
    } catch (error) {
      console.error(`Failed to send "${item}":`, error);
      // Choose to break (stop further requests) or continue here
      break;
    }
  }
}

// Start the sequential request process
sendItemsSequentially();

Key Takeaway

Even though Ajax is asynchronous, we’re not stuck letting all requests fire at once. By using Promises or async/await, we can explicitly control the order of execution—ensuring each request only starts after the previous one completes successfully (or handles failure appropriately).

内容的提问来源于stack exchange,提问作者ChuChu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:37:51