繁体   English   中英

调用异步函数以在 JavaScript 中按顺序执行

[英]Make calls to async function to be executed sequentially in JavaScript

如何实现send功能,以便calculate将按顺序执行,并保留调用顺序

async function calculate(value) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(value * value), 1)
  })
}

async function send(value) {
  return await calculate(value)
}
  • 在上一次调用完成之前,不应开始calculate的下一次调用。
  • calculate调用应该以完全相同的顺序到达。
  • 应正确返回await结果

当调用者忽略结果时,它应该以这种方式工作(我们总是返回结果并且不关心它是否被使用)

send(2)
send(3)

以及异步调用

;(async () => {
  console.log(await send(2))
  console.log(await send(3))
})()

聚苯乙烯

为什么它被否决了? 对于有状态的远程服务来说,这是一个完全合法的用例,其中calculate将是远程调用。 而且您必须保留顺序,因为远程服务是有状态的,结果取决于调用顺序。

这是我设置异步队列的方法,以便它按顺序处理事物,而不管它们如何调用:

function calculate(value) {
  var reject;
  var resolve;
  var promise = new Promise((r, rr) => {
    resolve = r;
    reject = rr;
  })

  queue.add({
    value: value,
    resolve: resolve,
    reject: reject
  });

  return promise;
}

var calcluateQueue = {
  list: [], // each member of list should have a value, resolve and reject property
  add: function(obj) {
    this.list.push(obj); // obj should have a value, resolve and reject properties
    this.processNext();
  },
  processNext: async function() {
    if (this.processing) return; // stops you from processing two objects at once
    this.processing = true;
    var next = this.list.unshift(); // next is the first element on the list array
    if (!next) return;
    try {
      var result = await doSomeProcessing(next.value);
      next.resolve(result);
      this.processNext();
    } catch(e) {
      next.reject(e);
      // you can do error processing here, including conditionally putting next back onto the processing queue if you want to
      // or waiting for a while until you try again
      this.processNext();
    }    
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM