我有一个非常简单的承诺,它执行,我得到返回响应,并在处理返回响应时,它就像函数永不退出一样。我的测试变得越来越简单,只是把它归结为基础知识,然而问题仍然存在 - 不能为我的生活看到它为什么会这样做。
isError = 0 ;
// validating corporate ID
if ($scope.installType == 1) {
$scope.errMsg = "Validating Corporate Business ID" ;
document.getElementById('errorMsg').style.textDecoration = 'blink' ;
return apiService.all()
.then(function(response){
var corpData = response[0] ;
if (corpData.rowCount == 1 && corpData.data[0].corpID == $scope.userObj.corp_ID) {
// theoretically a match was found
console.log("no error") ;
} else {
// no match was found
console.log("with error") ;
isError++ ;
}
console.log("isError: "+isError) ; // this prints to console
//return ; // had added this thinking it was stuck inside the promise, still didn't work
}) ;
console.log("hereA") ; // <-- never gets here
}
答案 0 :(得分:2)
该日志不会执行,因为它位于return语句之后。
isError = 0 ;
// validating corporate ID
if ($scope.installType == 1) {
$scope.errMsg = "Validating Corporate Business ID" ;
document.getElementById('errorMsg').style.textDecoration = 'blink' ;
return apiService.all() // <= watch this return statement
.then(function(response){
var corpData = response[0] ;
if (corpData.rowCount == 1 && corpData.data[0].corpID == $scope.userObj.corp_ID) {
// theoretically a match was found
console.log("no error") ;
} else {
// no match was found
console.log("with error") ;
isError++ ;
}
console.log("isError: "+isError) ; // this prints to console
//return ; // had added this thinking it was stuck inside the promise, still didn't work
}) ;
console.log("hereA") ; // <-- Code after a return never executes
}
将它放在return
之前的任何其他位置,它将按预期执行。我已经重新缩进了你的代码并对其进行了评论,希望它更容易理解。
为避免将来遇到这种麻烦,请考虑安装类似Eslint的内容并将其集成到IDE /编辑器中。 Its no-unreachable rule会直接警告你所遇到的问题。
编辑:
if ($scope.installType == 1) {
$scope.errMsg = "Validating Corporate Business ID" ;
document.getElementById('errorMsg').style.textDecoration = 'blink' ;
apiService.all() // <= removed return statement
.then(function(response){
var corpData = response[0] ;
if (corpData.rowCount == 1 && corpData.data[0].corpID == $scope.userObj.corp_ID) {
// theoretically a match was found
console.log("no error") ;
} else {
// no match was found
console.log("with error") ;
isError++ ;
}
console.log("isError: "+isError) ; // this prints to console
//return ; // had added this thinking it was stuck inside the promise, still didn't work
}) ;
console.log("hereA") ; // <-- this executes
}
答案 1 :(得分:2)
IT永远不会在那里,因为控制台日志不在您构建的功能链之内,而是在返回后发生。