簡體   English   中英

執行單行代碼后解決承諾

[英]Resolve Promise After Executing Single Line Of Code

我有一系列嘗試對齊的事件,但是我不明白如何在單行異步代碼之后解決承諾。 在這種情況下,我正在進行一個API調用,該調用解析為一個對象數組。 然后,我使用Object.assign()將對象數組轉換為對象對象。 完成后,我接下來要調用一個函數,該函數對對象的新對象進行處理。 轉換過程需要一些時間,我不確定如何將函數調用推遲到對象轉換之后。 我的無效代碼如下。

this.queryCodes().then(() => {
  new Promise((resolve) => {
    resolve(() => {
      // This code isn't executing.
      this.floorCodesLookup = Object.assign({}, ...this.floorCodes);
    });
  }).then((data) => {
    this.resolveCodesToDescriptions();
  });
});

resolve應該給你的異步操作,而不是要執行的代碼的結果。 您要執行的代碼不應放在resolve參數中,而應在回調中提供給promise構造函數。 因此,對於您的摘要:

this.queryCodes().then(() => {
  return new Promise((resolve) => {
    // Put the code you want to execute here...
    // Call resolve when your work is done, and pass it the result if there is one.
    resolve(/* maybe result here */);
  }).then((data) => {
    this.resolveCodesToDescriptions();
  });
});

還值得注意的是,您不需要使用promise構造函數,因為您已經鏈接了一個promise。 您可以:

this.queryCodes().then(() => {
  // Do additional work here...
  this.floorCodesLookup = Object.assign({}, ...this.floorCodes);
  return this.resolveCodesToDescriptions();
});

resolve()不將回調作為參數。 它以解析值作為參數。 不確定從何處獲得回調概念。 這就是從不調用回調的原因,因為它不是resolve()的受支持功能。

可能不需要在.then()處理程序內手動創建promise .then()並且可能是反模式 您在這里沒有顯示足夠的真實代碼來了解正在發生的事情,但這可能比所需的復雜得多。 從您顯示的代碼中,我認為您可以做到這一點:

this.queryCodes().then(() => {
   this.floorCodesLookup = Object.assign({}, ...this.floorCodes);
   this.resolveCodesToDescriptions();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM