2015-06-30 74 views
0

这里是我的代码:否则,如果语句会导致错误,而仅使用if语句不

function guaranteedPost(endpointId, wallPost, attempts){ 
    var attempts = attempts || 0 
    return graph.postAsync(endpointId + '/feed', wallPost) 
    .then(function(response){ 
    return response 
    }) 
    .catch(function(error){ 
    if(error.message != errorMessage){ 
     return Promise.reject(error.message) 
    } 
    console.log('Retry attempt #: ' + attempts) 
    if(attempts == 5){ 
     return Promise.reject('Too many errors') 
    } 
    // console.log(error) 
    return Promise.delay(5000).then(function(){  
     return guaranteedPost(endpointId, wallPost, attempts + 1) 
    }) 
    }); 
} 

,一切工作正常。

如果我改变第二,如果到否则,如果:

function guaranteedPost(endpointId, wallPost, attempts){ 
    var attempts = attempts || 0 
    return graph.postAsync(endpointId + '/feed', wallPost) 
    .then(function(response){ 
    return response 
    }) 
    .catch(function(error){ 
    if(error.message != errorMessage){ 
     return Promise.reject(error.message) 
    } 
    console.log('Retry attempt #: ' + attempts) 
    else if(attempts == 5){ //BLOWS UP 
     return Promise.reject('Too many errors') 
    } 
    // console.log(error) 
    return Promise.delay(5000).then(function(){  
     return guaranteedPost(endpointId, wallPost, attempts + 1) 
    }) 
    }); 
} 

这打击了我的代码有语法错误:

else if(attempts == 5){ 
    ^^^^ 
SyntaxError: Unexpected token else 

这究竟是为什么?我使用其他if语句遍历我的代码,并且我没有收到任何错误。我在测试中似乎没有做的事情可以让我解决这个错误。

+3

,因为'if'和'else if'之间有'console'。 – epascarello

+0

嗯,我不会真的称这是一个简单的印刷错误,考虑到错误是由Javascript的功能产生的,而不是错误的例子。我甚至明确表示它只使用if语句,而不使用else if语句。 – Antoine

回答

2

这是因为你之前else关键字有

console.log('Retry attempt #: ' + attempts) 

else关键字需要立即在if区块之后。

+0

我从来没有猜到这是原因,堆栈跟踪肯定没有帮助。非常感谢。 – Antoine

1

你应该从你的代码去掉这行之前其他

console.log('Retry attempt #: ' + attempts)