0
我有一個像下面的代碼:如何解決遞歸承諾?
function addNumberToFilename(filename) {
var newFilename = "";
var textInsideParentheses = filename.match(/\(([^)]+)\)/);
if (textInsideParentheses !== null && textInsideParentheses[1] !== undefined) {
// have parentheses
var numInParentheses = parseInt(textInsideParentheses[1]);
var nextNumInParentheses = numInParentheses + 1;
newFilename = filename.replace(/\(.*?\)/, String('(' + nextNumInParentheses + ')'))
} else {
// have not parentheses
var reForExtensionExtract = /(?:\.([^.]+))?$/;
var extension = reForExtensionExtract.exec(filename)[1];
var fileNameWithoutExtenstion = filename.replace(/\..+$/, '');
newFilename = fileNameWithoutExtenstion + '(1)' + '.' + extension;
}
checkIfFileExist(newFilename);
}
function checkIfFileExist(filename, path) {
return new Promise(function(resolve, reject) {
var fileWithThatFilenameFound = false;
local.files.listFolder({
"path": "default:\\",
"filter": ["Img"]
}, {
success: function (result) {
result.map(function (elem) {
if (elem.itemName === filename) { // file with that filename exists
// so add parentheses or increase them
fileWithThatFilenameFound = true;
addNumberToFilename(filename);
}
});
if (!fileWithThatFilenameFound) {
// end of the recursion chain! let's resolve finally
resolve(filename);
}
}
});
});
}
...
checkIfFileExist(snapshot.filename + '.jpg').then(function(newFileName) {
local.images.save({
fileName: newFileName
})
});
但我有問題這一點。
如果根本沒有遞歸(文件名不存在,所以解析在第一個promise中執行),一切正常。但如果文件名存在(並且鏈是checkIfFileExist - > addNumberToFilename - > checkIfFileExist - > resolve())resolve()不起作用。
爲什麼?我如何解決遞歸承諾?
我改變了'checkIfFileExist(newFilename);'''在addNumberToFilename函數中返回checkIfFileExist(newFilename);'但它不起作用。 – bialasikk