Then not working just after fetch


#1

I have one function which calls another function which return promise.
But instead of calling fetch.then(…) it executes next line under function calling and then executes then or catch.
does anyone have idea about this weird behavior?

ex.

  isvalidUser = function(uid,pwd)
 {
      return fetch(config.loginApiUrl + "?uid=" +uid +"&pwd="+pwd)
    .then((response) => {
        if(response.ok)
        {
        return response.json();
        }else {
            return Promise.reject({status: response.status, data});
          }
    }).then(function(data) {
        console.log("data l:" + data.length);
        for(var i=0;i<=data.length;i++)
        {
            console.log("third in");
         viewModel.get("roleId").push(data[i].securityRoleId);
         viewModel.get("UserName").push(data[i].name);
        }
    }).catch(handleErrors); 
  } 

function call on another file

 btn_click()
{
   login.isvaliduser(id,pwd);-----------------------1
   var rid = login.get("roleId");---------------------2
}

in this case it execute second line first then execute then(…) of validUser()

please help me it happens in each and every api calling of my project.


#2

Hi @radhe12
Can you recreate the problem you are facing in a playground app?


#3

Thanks! but it’s difficult call api there And I am able to find solution of my problem.


#4

problem solved?
In that case, can you share the solution?


#5

At the time of function calling call then and catch the error if there any

 login.isvaliduser(id,pwd).then(function(){
           var rid=login.get("roleId");
    }).catch(function (error) {
          console.error("User Validation Error:"+error);
   });