首页 > 解决方案 > 使用 React 实现顺序作业队列

问题描述

我正在寻求实现一个作业队列,以确保即使每个 API 调用都可能花费可变的时间,也可以按照输入的输入项的顺序返回来自 API 的响应。

请参阅此处的代码和框https://codesandbox.io/s/sequential-api-response-eopue - 当我item在输入字段中输入诸如1、12、1234、12345 并按Enter 时,它会转到我返回的模拟后端item+-response表示相应输入的输出。但是,我在每次调用时使用了不同的超时时间Math.random()来模拟 API 可能花费不确定时间的真实场景。

电流输出

processing:  1 
processing:  12 
processing:  123 
processing:  1234 
processing:  12345 
processing:  123456 
response: 1234-response 
response: 12-response 
response: 123456-response 
response: 123-response 
response: 1-response 
response: 12345-response 

预期输出 我想看到的输出是

processing:  1 
processing:  12 
processing:  123 
processing:  1234 
processing:  12345 
processing:  123456 
response: 1-response 
response: 12-response 
response: 123-response 
response: 1234-response 
response: 12345-response 
response: 123456-response 

我的尝试: 我试图实现该函数(它是对生成上述错误输出getSequentialResponse的函数的包装)。getNonSequentialResponse此函数将item用户输入的内容添加到 aqueue中,并且仅在释放queue.shift()锁变量时执行,通过指示当前的承诺已解决并准备处理下一个承诺。在此之前,它会在处理当前项目时循环等待。我的想法是,由于元素总是从头部删除,因此项目将按照输入的顺序进行处理。_isBusygetNonSequentialResponsewhile

错误: 但是,据我了解,这是错误的方法,因为 UI 线程正在等待并导致错误潜在无限循环:超过 10001 次迭代。您可以通过创建一个 sandbox.config.json 文件来禁用此检查。

标签: asynchronousweb-workerjob-queue

解决方案


这里有几件事要考虑。

  1. while 循环在这里是错误的方法——因为我们在 JavaScript 中使用异步操作,我们需要记住事件循环是如何工作的(如果你需要入门,这里是一个很好的讨论)。您的 while 循环将占用调用堆栈并阻止事件循环的其余部分(包括处理 Promise 的 ES6 作业队列和处理超时的回调队列)发生。
  2. 因此,如果没有 while 循环,JavaScript 中有没有一种方法可以控制何时解析一个函数,以便我们可以进入下一个函数?当然——这是承诺!我们将把工作包装在一个 Promise 中,并且只有在我们准备好继续前进时才解决该 Promise,或者如果出现错误则拒绝它。
  3. 既然我们在谈论一个特定的数据结构,一个队列,让我们用一些更好的术语来改进我们的心智模型。我们不是在“处理”这些工作,而是在“排队”它们。如果我们同时处理它们(即“处理 1”、“处理 2”等),我们就不会按顺序执行它们。
export default class ItemProvider {
  private _queue: any;
  private _isBusy: boolean;

  constructor() {
    this._queue = [];
    this._isBusy = false;
  }

  public enqueue(job: any) {
    console.log("Enqueing", job);
    // we'll wrap the job in a promise and include the resolve and reject functions in the job we'll enqueue, so we can control when we resolve and execute them sequentially
    new Promise((resolve, reject) => {
      this._queue.push({ job, resolve, reject });
    });
    // we'll add a nextJob function and call it when we enqueue a new job; we'll use _isBusy to make sure we're executing the next job sequentially
    this.nextJob();
  }

  private nextJob() {
    if (this._isBusy) return;
    const next = this._queue.shift();
    // if the array is empty shift() will return undefined
    if (next) {
      this._isBusy = true;
      next
        .job()
        .then((value: any) => {
          console.log(value);
          next.resolve(value);
          this._isBusy = false;
          this.nextJob();
        })
        .catch((error: any) => {
          console.error(error);
          next.reject(error);
          this._isBusy = false;
          this.nextJob();
        });
    }
  }
}

现在在我们的 React 代码中,我们将使用您创建的辅助函数创建一个伪异步函数并将工作排入队列!

import "./styles.css";
import ItemProvider from "./ItemProvider";
// import { useRef } from "react";

// I've modified your getNonSequentialResponse function as a helper function to return a fake async job function that resolves to our item
const getFakeAsyncJob = (item: any) => {
  const timeout = Math.floor(Math.random() * 2000) + 500;
  // const timeout = 0;
  return () =>
    new Promise((resolve) => {
      setTimeout(() => {
        resolve(item + "-response");
      }, timeout);
    });
};

export default function App() {
  const itemProvider = new ItemProvider();

  function keyDownEventHandler(ev: KeyboardEvent) {
    if (ev.keyCode === 13) {
      const textFieldValue = (document.getElementById("textfieldid") as any)
        .value;

      // not sequential
      // itemProvider.getNonSequentialResponse(textFieldValue).then((response) => {
      //   console.log("response: " + response);
      // });
      
      // we make a fake async function tht resolves to our textFieldValue
      const myFakeAsyncJob = getFakeAsyncJob(textFieldValue);
      // and enqueue it 
      itemProvider.enqueue(myFakeAsyncJob);
    }
  }

  return (
    <div className="App">
      <input
        id="textfieldid"
        placeholder={"Type and hit Enter"}
        onKeyDown={keyDownEventHandler}
        type="text"
      />

      <div className="displaylabelandbox">
        <label>Display box below</label>
        <div className="displaybox">hello</div>
      </div>
    </div>
  );
}

这是代码框。


推荐阅读