node.js - 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,依此类推。
有多种方法可以确定是否需要再次运行:
- 将数组的长度与生成的数量 countProducts 进行比较
- 通过将生成的 countProducts 数除以 1000 (ceil()) 来确定正手击球次数
- 将最后找到的名称与新的最后找到的名称进行比较
我只是不知道如何循环和在哪里。我假设解决方案是通过添加一个辅助函数找到的,但是当我尝试时我陷入了不可用的值等等。
您不必解决我的问题,但如果有人可以提供所需结构的示例或描述此结构的一些互联网资源,我将不胜感激。我发现的示例不使用以前运行的值。
解决方案
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);
});
推荐阅读
- c# - 动态引用 IQueryable 中的实体框架列
- javascript - 当多语言存储在集合中时如何使用 Mongoose 获取数据
- scala - 在项目中查找未使用的案例类
- java - SPRING BOOT 注释:是否需要
- solrcloud - 使用 SolrNet 获取 Solr 状态
- python - For循环没有使用pandas DataFrame给出预期的输出
- python - 在 tensorflow 中实现简单的线性代数运算
- facebook - 现在为 facebook 在 maltego 中转换显示
- java - 为什么我在实体 A 的仓库中得到 UnsatisfiedDependencyException 而不是在实体 B 中得到 UnsatisfiedDependencyException,而它们之间几乎没有区别?
- android - app_release.apk 的 Google oauth 中的问题,app_debug.apk 工作正常