如何以“原始顺序”组装 JavaScript 异步获取结果

时间:2021-03-12 20:35:10

标签: javascript asynchronous fetch

异步的好处是,它加快了获取速度,我们首先得到可用的东西,而不是服务器来响应。

但这打乱了请求的顺序,在这种情况下这对我很重要。

我想抓取一个连续故事的不同部分,所以顺序是必须的。

这是我所做的:

async function getSingle(url) {
    await fetch(url).then(function (response) { 
        return response.text();
    }).then(function (html) {    
        var output = document.querySelector('.output');
        output.innerHTML=html;          
        text += "\n" + document.querySelector('.post-body').innerText;
    });
}

它完美地获取了一切,但是当我为多个 URL 调用它时,它返回它们无序。

[这里是初学者,所以如果它真的很琐碎,请原谅。]

2 个答案:

答案 0 :(得分:1)

您的功能与(我建议完全使用 async/await

async function getSingle(url) {
  const response = await fetch(url);
  const html = await response.text();

  const output = document.querySelector('.output');
  output.innerHTML = html;
  text += "\n" + document.querySelector('.post-body').innerText; // "text" ???
}

为了保持顺序,可以通过for循环按顺序调用函数,请求会被一一调用:

const urls = ['url1', 'url2'];

for (const url of urls) {
  await getSingle(url);
}

如果你想并行调用请求,让我们使用 Promise.all。但是你必须重构你的函数 - 它会返回 html 字符串:

async function getSingle(url) {
  const response = await fetch(url);
  const html = await response.text();
  return html
}

const htmls = await Promise.all(urls.map(url => getSingle(url));
for (const html of htmls) {
  const output = document.querySelector('.output');
  output.innerHTML = html;
  text += "\n" + document.querySelector('.post-body').innerText; // "text" ???
}

答案 1 :(得分:0)

您可以尝试跟踪它们发送的顺序,然后当您收到响应时,尝试将您的 html 以相同的顺序添加到它们的 dom 中。像这样(我没有测试过):

let order = [];
let index = 0;
let completed_index=0;

async function getSingle(url) {
    let i=index++;
    order[i] = {index:i}
    await fetch(url).then(function (response) { 
        order[i] = response.text();
    }).then(function (html) {
    while(order[completed_index]!==undefined{
        completed_index++;
        var output = document.querySelector('.output');
        output.innerHTML=order[completed_index];          
        text += "\n" + document.querySelector('.post-body').innerText;
        }
    });
}

你可能想在之后清除数组