否则if语句会导致错误,而仅使用if语句不会

时间:2015-06-30 16:41:46

标签: javascript

这是我的代码:

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:

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语句遍及我的代码,我没有收到任何错误。我在测试中似乎没有任何东西可以让我解决这个错误。

2 个答案:

答案 0 :(得分:2)

这是因为你有

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

else关键字之前。 else阻止后需要if关键字。

答案 1 :(得分:1)

您应该在其他阻止

之前从代码中删除此行
console.log('Retry attempt #: ' + attempts)