这是我的代码:
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)
})
});
}
一切正常。
如果我将第二个 if 更改为 else 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)
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
为什么会发生这种情况?我在代码中使用 else if 语句,并且没有收到任何错误。我在测试中似乎无法做任何事情来解决这个错误。
最佳答案
因为你有
console.log('Retry attempt #: ' + attempts)
在 else
关键字之前。 else
关键字必须紧接在 if
block 之后。
关于javascript - else if 语句会导致错误,而仅使用 if 语句则不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31143830/