2016-08-16 112 views
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()不起作用。

爲什麼?我如何解決遞歸承諾?

+0

我改變了'checkIfFileExist(newFilename);'''在addNumberToFilename函數中返回checkIfFileExist(newFilename);'但它不起作用。 – bialasikk

回答

0

因爲你必須回到你的承諾:

function addNumberToFilename(filename) { 

    //... 
    return checkIfFileExist(newFilename); 
} 

checkIfFileExist(snapshot.filename + '.jpg') 
    .then((fileName) => local.images.save({ fileName })) 

評論後編輯:

function checkIfFileExist(filename) { 
    //simplyfied a bit 
    return new Promise(function (resolve, reject) { 
     resolve false; 
    }) 
} 

function saveFile(newFileName) { 

    return local.images.save({ 
     fileName: newFileName 
    }) 
    // the second argument wasn't useful at all 
} 

function save() { 

    return checkIfFileExist(snapshot.filename + '.jpg') 
     .then(saveFile) 
     .catch(err => console.error(err)) 
} 

我看到周圍散落許多問題:

  • local.images.save是一個函數?
  • 它返回一個承諾?
  • 承諾是履行?
+0

它不起作用。我在主要checkIfFileExist調用上的代碼是:https://jsfiddle.net/pv92v9h0/ – bialasikk