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

问题描述 投票:-2回答:1

如何实现send功能,以便顺序执行calculate,并保留命令的调用?

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

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

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

send(2)
send(3)

也用于异步调用

;(async () => {
  console.log(await send(2))
  console.log(await send(3))
})()
javascript
1个回答
0
投票

这是我设置异步队列的方式,以便无论如何调用,它都会按顺序处理事物:

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();
    }    
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.