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

调用异步函数以在JavaScript中顺序执行,javascript,Javascript,如何实现send函数,以便在保留调用顺序的情况下按顺序执行计算 async function calculate(value) { return new Promise((resolve) => { setTimeout(() => resolve(value * value), 1) }) } async function send(value) { return await calculate(value) } 在上一次调用完成之前,不应启动calcula

如何实现send函数,以便在保留调用顺序的情况下按顺序执行计算

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

async function send(value) {
  return await calculate(value)
}
在上一次调用完成之前,不应启动calculate的下一次调用。 调用calculate的顺序应该完全相同。 应正确返回等待的结果。 当调用者忽略结果时,它应该是这样工作的,我们总是返回结果,而不关心它是否被使用

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();
    }    
  }
};

删除您的问题,然后在10分钟后发布一个文本几乎相同的新问题,这不是一个好办法。您要做的是设置一个异步队列,以便同步调用不会相互重叠。我根本不明白您在哪里调用calculate,或者为什么需要设置超时。但是你描述的行为听起来和Wait完全一样。在第一个调用send两次的示例中,您只是没有等待他们。也许你可以制作一个完整的、可运行的示例,演示你如何处理异步操作,这些操作应该等待,但没有?@David关于不调用-请检查示例,我更新了它。calculate表示远程web服务,可以用两种方式调用它-当我们想对响应执行某些操作时使用wait,当我们只想调用它并忽略结果时不使用wait。@Alexeypterushin:而不使用wait-无论您是否想使用结果,省略wait专门告诉代码不要等待操作。你真的在问如何在不等待的情况下等待手术吗?请注意:这是我编造的。它可能不是最好的解决方案,在使用它之前,您应该测试基于它的任何实现。谢谢。只是想知道-如果在next.reject中抛出异常会发生什么-是否可以像没有队列一样保留相同的行为?我不确定您的意思。