Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/delphi/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Node JS promise-使用前一次运行的参数多次运行函数_Node.js_Promise - Fatal编程技术网

Node.js Node JS promise-使用前一次运行的参数多次运行函数

Node.js Node JS promise-使用前一次运行的参数多次运行函数,node.js,promise,Node.js,Promise,在我的演讲中,我通过看这个社区提供的一些例子来解决我的承诺问题。我希望这个问题也能很容易解决,尽管我就是想不起来。这是我有生以来第一次体会到,流利地使用PHP语言是一种负担 我的代码如下所示: let getProducts = function(){ countProducts .then(function(number){ var name = ''; let list = []; getProductNames(name) .

在我的演讲中,我通过看这个社区提供的一些例子来解决我的承诺问题。我希望这个问题也能很容易解决,尽管我就是想不起来。这是我有生以来第一次体会到,流利地使用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
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);
              } 
            });
        }
  );
}
getProductNames函数如下所示:

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
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调用的问题在于它需要一个productname作为开始。第一次运行没有名称,这将返回第一个1000。对于第二次运行,我需要最后找到的运行1的productname,对于运行3,我需要最后找到的运行2的productname,依此类推

有不同的方法来确定是否需要再次运行:

  • 将数组长度与生成的countProducts数进行比较
  • 将countProducts生成的次数除以1000(ceil()),确定正手击球的次数
  • 将上次找到的名称与新的上次找到的名称进行比较
我只是不知道如何循环和在哪里。我假设解决方案是通过添加一个helper函数来找到的,但是当我尝试时,我发现值不可用等等


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

我在需要的地方添加了注释,以便更好地理解代码。随便问什么

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);
});
注意:此代码未经测试,可能无法正常工作。这只是向你展示如何真正做到这一点

注1:您可能还想看看
asyncwait
,它们与promise相同,但在语法上更具可读性和清晰性

let getProducts = function() {
  // return your promise, you may want to getProducts.then()
  return countProducts() 
    .then(function(number) {
      return getProductNames(number);
    })
    .catch(function(err) { // always put a catch
       console.log('there was an error', err)
    })
}


// make your getProductsName take in number value
// the name it takes is empty by default, we will provide name when we recursively call it
let getProductNames = function(number, name = ''){
  // check if your number is less than -1000 here , why ? keep reading the code
  if (number < -1000) return [];
  const nameCount = 1000;
  let names = []
  return callAPI({name, nameCount})
    .then(function(namesFromCallAPI) {
       names = names.concat(namesFromCallAPI); // you can concat two arrays at once
       // I do not know why you are poping the names, since it will mutate the array
       // use any one as per requirement
       let newName = names.pop();
       // OR let newName = names[names.length-1]; which will not mutate the array
       // recursively call the function by decreasing it by your nameCount
       // when your number is 500, it can still call but the result will be -500, which will run
       // in the next iteration -500-1000 will be -1500 which is < -1000 (explanation of base condition)
       return getProductNames(number - nameCount, newName)
    })
    .then(function(res) {
      // the result from getProductNames is again concatinated to our names and returned
      return names.concat(res);
    })
    .catch(function(err) {
       // always put a catch in your chain
       console.log('There was an error in our recursive function', err);
    })
}


// make a separate function that would api call
// put any parameters that you may need to make customizable here
let callAPI = function(params) {
  return new Promise(function(resolve,reject) {
    xyz.api.checkProducts(params.name, params.nameCount, function(err, names){
      if (err){
        reject(err);
      } else {
        resolve(names);
      } 
    });
  })
}
let getProducts=function(){
//回报你的承诺,你可能想要获得产品。然后()
退货产品()
.然后(功能(编号){
返回getProductNames(编号);
})
.catch(函数(err){//始终放置一个catch
console.log('发生错误',err)
})
}
//让您的getProductsName接受数值
//它采用的名称默认为空,我们将在递归调用它时提供名称
让getProductNames=函数(编号,名称=“”){
//检查你的号码是否小于-1000,为什么?继续阅读代码
如果(数字<-1000)返回[];
常量名称计数=1000;
让名称=[]
返回callAPI({name,nameCount})
.then(函数(namesFromCallAPI){
names=names.concat(namesFromCallAPI);//您可以同时concat两个数组
//我不知道你为什么要用这些名字,因为它会改变数组
//根据需要使用任何一种
让newName=names.pop();
//或者让newName=names[names.length-1];这不会改变数组
//通过按名称计数递减来递归调用函数
//当您的号码是500时,它仍然可以呼叫,但结果将是-500,这将运行
//在下一次迭代中-500-1000将是-1500,即<-1000(基本条件的解释)
返回getProductNames(编号-nameCount,newName)
})
.然后(功能(res){
//getProductNames的结果再次与我们的名称关联并返回
返回名称。concat(res);
})
.catch(函数(err){
//总是在你的链条上挂一个钩子
log('我们的递归函数中有一个错误',err);
})
}
//创建一个单独的函数来调用api
//在此处放置您可能需要定制的任何参数
让callAPI=函数(params){
返回新承诺(功能(解决、拒绝){
xyz.api.checkProducts(params.name、params.nameCount、函数(err、names){
如果(错误){
拒绝(错误);
}否则{
决定(姓名);
} 
});
})
}

为了更好地理解代码,我在需要的地方添加了注释。随便问什么

注意:此代码未经测试,可能无法正常工作。这只是向你展示如何真正做到这一点

注1:您可能还想看看
asyncwait
,它们与promise相同,但在语法上更具可读性和清晰性

let getProducts = function() {
  // return your promise, you may want to getProducts.then()
  return countProducts() 
    .then(function(number) {
      return getProductNames(number);
    })
    .catch(function(err) { // always put a catch
       console.log('there was an error', err)
    })
}


// make your getProductsName take in number value
// the name it takes is empty by default, we will provide name when we recursively call it
let getProductNames = function(number, name = ''){
  // check if your number is less than -1000 here , why ? keep reading the code
  if (number < -1000) return [];
  const nameCount = 1000;
  let names = []
  return callAPI({name, nameCount})
    .then(function(namesFromCallAPI) {
       names = names.concat(namesFromCallAPI); // you can concat two arrays at once
       // I do not know why you are poping the names, since it will mutate the array
       // use any one as per requirement
       let newName = names.pop();
       // OR let newName = names[names.length-1]; which will not mutate the array
       // recursively call the function by decreasing it by your nameCount
       // when your number is 500, it can still call but the result will be -500, which will run
       // in the next iteration -500-1000 will be -1500 which is < -1000 (explanation of base condition)
       return getProductNames(number - nameCount, newName)
    })
    .then(function(res) {
      // the result from getProductNames is again concatinated to our names and returned
      return names.concat(res);
    })
    .catch(function(err) {
       // always put a catch in your chain
       console.log('There was an error in our recursive function', err);
    })
}


// make a separate function that would api call
// put any parameters that you may need to make customizable here
let callAPI = function(params) {
  return new Promise(function(resolve,reject) {
    xyz.api.checkProducts(params.name, params.nameCount, function(err, names){
      if (err){
        reject(err);
      } else {
        resolve(names);
      } 
    });
  })
}
let getProducts=function(){
//回报你的承诺,你可能想要获得产品。然后()
退货产品()
.然后(功能(编号){
返回getProductNames(编号);
})
.catch(函数(err){//始终放置一个catch
console.log('发生错误',err)
})
}
//让您的getProductsName接受数值
//它采用的名称默认为空,我们将在递归调用它时提供名称
让getProductNames=函数(编号,名称=“”){
//检查你的号码是否小于-1000,为什么?继续阅读代码
如果(数字<-1000)返回[];
常量名称计数=1000;
让名称=[]
返回callAPI({name,nameCount})
.then(函数(namesFromCallAPI){
names=names.concat(namesFromCallAPI);//您可以同时concat两个数组
//我不知道你为什么要用这些名字,因为它会改变数组
//根据需要使用任何一种
让newName=names.pop();
//或者让newName=names[names.length-1];这不会改变数组
//通过按名称计数递减来递归调用函数
//当您的号码是500时,它仍然可以呼叫,但结果将是-500,这将运行
//在下一次迭代中-500-1000将是-1500,即<-1000(基本条件的解释)
返回getProductNames(编号-nameCount,newName)
})
.然后(功能(res){
//getProductNames的结果是