首页 > 解决方案 > Node JS promise - 使用以前运行的参数多次运行函数

问题描述

在我之前的帖子中,通过查看这个社区提供的一些示例,我能够解决我的 Promise 问题。我希望这个问题也很容易解决,尽管我无法理解它。我有生以来第一次体验到流利的 PHP 语言是一种负担。

我的代码如下所示:

let getProducts = function(){
  countProducts
    .then(function(number){
      var name = '';
      let list = [];
      getProductNames(name)
        .then(function(names){
          names.forEach(function(el){
            list.push(el);
          });
          name = list.pop();
          getProductNames(name)
            .then(function(names){
              names.forEach(function(el){
                list.push(el);
              });
              ... and some more code to put the names in a table

getProductNames 函数如下所示:

var getProductNames = 
function(name) {
  return new Promise(
        function(resolve, reject){
            xyz.api.checkProducts(name, 1000, function(err, names){
              if (err){
                reject(err);
              } else {
                resolve(names);
              } 
            });
        }
  );
}

这是有效的,因为我知道我的产品少于 2000 个,每次检查返回 1000 个产品,所以我必须运行两次 getProductNames 函数。

我正在寻找一种将其变为循环的方法,以便它自动运行所需的运行次数。

api 调用的问题在于它需要以产品名称开头。第一次运行没有名称,它返回第一个 1000。第二次运行我需要运行 1 的最后找到的产品名称,运行 3 我需要最后找到的产品名称 2,依此类推。

有多种方法可以确定是否需要再次运行:

我只是不知道如何循环和在哪里。我假设解决方案是通过添加一个辅助函数找到的,但是当我尝试时我陷入了不可用的值等等。

您不必解决我的问题,但如果有人可以提供所需结构的示例或描述此结构的一些互联网资源,我将不胜感激。我发现的示例不使用以前运行的值。

标签: node.jspromise

解决方案


let getProducts = function () {
    let list = [];
    const fn = function (name, number) {
        return getProductNames(name).then(function (names) {
            names.forEach(function (el) {
                list.push(el);
            });

            if(list.length >= number || names.length == 0) {
                return list;
            }

            return fn(list.pop(), number); // Add promise to your chain
        });
    }
    return countProducts.then(function (number) {
        return fn('', number);
    });
}

// Use
getProducts().then(function(items) {
    console.log(items.length);
}, function(err) {
    console.error(err);
});

推荐阅读