如何解决递归承诺?

时间:2016-08-16 16:03:17

标签: javascript recursion promise ecmascript-6 es6-promise

我的代码如下:

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
    })
});

但我对此有疑问。

如果根本没有递归(文件名不存在,那么解析是在第一个承诺中执行)一切正常。但是如果文件名存在(并且链是checkIfFileExist - > addNumberToFilename - > checkIfFileExist - > resolve()),则resolve()不起作用。

为什么呢?我该如何解决递归承诺?

1 个答案:

答案 0 :(得分: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是一个功能?
  • 它会返回一个承诺吗?
  • 承诺是否实现?