【发布时间】:2018-10-11 14:22:08
【问题描述】:
我有一个这样的递归函数
function missingItemsPromise() {
return new Promise(resolve => {
if (missingItems == 0) {
console.log('resolves');
console.log(products);
return resolve();
} else {
page++;
url = getUrl(id, page);
http.get(url, function(xres) {
xres.setEncoding('utf8');
xres.on('data', function (xtraBody) {
console.log('calling');
var xtraJson = JSON.parse(xtraBody);
var xtraProducts = xtraJson['products'];
products = products.concat(xtraProducts);
productsLength = products.length;
missingItems = total - productsLength;
missingItemsPromise();
});
});
}
});
};
我正在像使用它一样使用它
getInitial.
then(missingItemsPromise).
then(() => {
console.log('hello');
});
我注意到 hello 永远不会返回,因为我怀疑我在递归调用中创建了多个 Promise,但我不确定如何返回。
如何返回每个递归创建的承诺?
编辑:
function missingItemsPromise() {
return new Promise(resolve => {
if (missingItems == 0) {
console.log('resolves');
return resolve();
} else {
page++;
url = getUrl(id, page);
http.get(url, function(xres) {
xres.setEncoding('utf8');
xres.on('data', function (xtraBody) {
console.log('calling');
var xtraJson = JSON.parse(xtraBody);
var xtraProducts = xtraJson['products'];
products = products.concat(xtraProducts);
productsLength = products.length;
missingItems = total - productsLength;
missingItemsPromise();
resolve();
});
});
}
});
};
结果
calling
hello <----notice here that it's already resolving once the first call resolve
is called
calling
calling
resolves
【问题讨论】:
-
您需要在
else{}块中添加resolve/reject。 -
您确定没有引发异常吗?为什么不也添加一个
catch来查看它? -
我尝试在递归调用之后添加一个解析,但意识到随着另一个递归调用的继续,外部承诺将解析导致 hello 在递归函数真正完成之前被调用
-
在
else块中,尝试用missingItemsPromise().then(resolve)替换最后两行。
标签: javascript node.js recursion promise