簡體   English   中英

循環運行一個函數,直到

[英]Run a function in a loop until

我目前正在嘗試循環運行一個函數。
無法弄清楚,這是我嘗試過的:

do {
  queryLastCursor(lastCursor).then(lastCursorResults => {
    if (lastCursorResults.hasNext = false) {
      hasNextPage = false;
    }
    console.log(hasNextPage);
  })
} while (hasNextPage);

queryLastCursor是一種調用 API 的方法。 當它返回數據時,它的值為hasNext如果它返回 false 那么我想將hasNextPage設置為false 預期的行為是它一次又一次地運行該函數,直到我們得到結果hasNext = false 知道我做錯了什么嗎?

如果您想在循環中執行異步過程,我建議遞歸執行:

const runQuery = () => {
  queryLastCursor(lastCursor)
    .then(result => {
      if (result.hasNext) {
        // recursively call itself if hasNext is true 
        runQuery();
      }
    });
}

runQuery();

假設您想返回一些數據,您可以執行以下操作:

const runQuery = async (data) => {
  return queryLastCursor(lastCursor)
    .then(result => {
      if (!data) {
        data = [];
      }

      // assuming you are returning the data on result.data
      data.push(result.data);

      if (result.hasNext) {
        // recursively call itself if hasNext is true 
        return runQuery(data);
      }

      retun data;
    });
}

runQuery() 
  .then(data => {
    // data should be an array of all the data now
  });

我會做這樣的事情:

const callApi = async () => {
    let result = await someMagic();
    while (result.hasNext) {
        doSomethingwith(result);
        result = await someMagic();
    }
    return result;
};
const myResult = await callApi();

雖然這看起來有風險,但我們總是得到 hastNext = true 是什么? 一些安全性似乎很好,比如 while 循環中的循環限制。

暫無
暫無

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

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