簡體   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