javascript - Node.js 从 do while 循环中调用异步函数

标签 javascript node.js asynchronous async-await do-while

我想从 do while 循环中调用异步函数,并且仅当该函数不返回值时才退出。 有没有一种方法可以管理这个问题,而不必在回调之外实际等待

下面的代码显然总是在第一个循环中退出,因为在评估 while () 时函数尚未回调:

var i = 0;
do {
  var foundListing;
  if (i) {
    listing.slug = listing.slug + '-' + (i + 1);
  }
  listingService.getListingBySlug(listing, function(error, pFoundListing) {
    if (error) {
      return callback(util.errorParser(error));
    } else if (Object.keys(pFoundListing).length) {
      foundListing = pFoundListing;
      i++;
    }
  });
  //Do I have to wait here???
} while (foundListing && Object.keys(foundListing).length);

澄清: 这里的重点是生成一个独特的 slug。如果 slug 已经存在,我会附加一个数字并再次检查它是否存在。当我找到还不存在的数字时,我就完成了。

更新: 我找到了一种使用递归的方法。我将工作片段发布为 answer .

最佳答案

我无法测试它,但也许递归函数应该可以:

const listingService = {
  getListingBySlug(listing, callback) {
    setTimeout(() => {
      if (listing.slug === 'listing-5') {
        callback(
          false,
          {
            name: 'Listing 1',
            slug: 'listing-1',
          }
        );
      }
      else {
        callback(false, {});
      }
    }, 1000);
  },
};

function checkListingExists(slug) {
  return new Promise((resolve, reject) => {
		const listing = { slug };
    listingService.getListingBySlug(listing, (error, pFoundListing) => {
      if (error) {
        reject(error);
      } else if (Object.keys(pFoundListing).length) {
        resolve(pFoundListing);
      } else {
        resolve(false);
      }
    });
  });
}

function nextListing(prefix, index) {
  checkListingExists(prefix + '-' + index)
  .then((listing) => {
    if (listing === false) {
      nextListing(prefix, index + 1);
    } else {
      console.log(listing);
    }
  })
  .catch(() => {
    // deal with error response
  });
}

nextListing('listing', 0);

关于javascript - Node.js 从 do while 循环中调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41693437/

相关文章:

javascript - 用模拟函数替换 nodejs 模块中的函数

c# - 从异步回调调用同步方法调用?

javascript - 为什么我们需要 webdriver 的 javaScript 执行器?

关于 form.elements 的 JavaScript

node.js - 如何在kibana中安装newrelic

c# - 我应该使用什么形式的任务控制来使用 SignalR 处理 MVC 中长时间运行的进程

javascript - 从 Render 中的循环获取变量到 ReactJS 中的 componentDidMount() 中,并将该变量放入查询参数中

javascript - 在 Canvas 上绘制背景图像

javascript - JSFiddle 上的 Github 存储库中缺少显示 Javascript 演示

javascript - 我可以在一个托管服务中托管我的前端,而在其他地方托管后端吗?