简体   繁体   中英

Promise resolve and reject in javascript

I'm trying to build a mobile application on NativeScript where I've created a class for authorization which has a login() function which has following codes:

export default class NitsEditorAuth {
    //Finding logged-in user.
    isLoggedIn() {
        return store.getters.access_token ? true : false;
    }
    //For Login user
    login(user) {
        const postData = {
            grant_type: 'password',
            username: user.email,
            password: user.password,
            client_id: clientId,
            client_secret: clientSecret,
            scope: '',
            provider: provider
        }
        const authUser = {}
        axios.post(authUrl, postData).then(response => {
            if(response.status === 200)
            {
                authUser.access_token = response.data.access_token;
                authUser.refresh_token = response.data.refresh_token;
                axios.get(apiUrl + 'user/log', {headers: getHeader()}).then(response => {
                    if(response.status === 200){
                        authUser.email = response.data.email;
                        authUser.first_name = response.data.first_name;
                        authUser.last_name = response.data.last_name;
                        authUser.userRole = response.data.role;
                        store.commit('save', authUser);
                        return new Promise(function (resolve, reject) {
                            resolve('Login successful')
                        });
                    }
                })
            }
        })
        .catch((err) => {
            if(err.response.status === 401){
//                this.error = err.response.data.message
                return new Promise(function (resolve, reject) {
                    reject('Validation error')
                });
            }
            else
                return new Promise(function (resolve, reject) {
                    reject('Something went wrong')
                });
        })
    }

}

I included this very class in my main.js file as:

const nitsEditorAuth = new NitsEditorAuth();
Vue.prototype.$nitsEditorAuth = nitsEditorAuth;

And I'm calling this function inside my Vue-methods like:

login() {
    this.$nitsEditorAuth
        .login(this.user)
        .then(() => {
           this.processing = false;
           this.$navigateTo(Home, { clearHistory: true });
        })
        .catch(() => {
           this.processing = false;
           this.alert(
              "Unfortunately we could not find your account."                   
           );
        });
},

But I'm getting error stating that:

TypeError: Cannot read property 'then' of undefined. Frame: function:'login'

Help me out with this. Thanks.

Easy fix would be just wrap a promise out side the function. And remove the rest. For example.

javascript node.js vue.js nativescript nativescript-vue
I'm trying to build a mobile application on NativeScript where I've created a class for authorization which has a login() function which has following codes:

export default class NitsEditorAuth {
    //Finding logged-in user.
    isLoggedIn() {
        return store.getters.access_token ? true : false;
    }
    //For Login user
    login(user) {
        const postData = {
            grant_type: 'password',
            username: user.email,
            password: user.password,
            client_id: clientId,
            client_secret: clientSecret,
            scope: '',
            provider: provider
        }
return new Promise(function (resolve, reject) {
        const authUser = {}
        axios.post(authUrl, postData).then(response => {
            if(response.status === 200)
            {
                authUser.access_token = response.data.access_token;
                authUser.refresh_token = response.data.refresh_token;
                axios.get(apiUrl + 'user/log', {headers: getHeader()}).then(response => {
                    if(response.status === 200){
                        authUser.email = response.data.email;
                        authUser.first_name = response.data.first_name;
                        authUser.last_name = response.data.last_name;
                        authUser.userRole = response.data.role;
                        store.commit('save', authUser);

                            resolve('Login successful')

                    }
                })
            }
        })
        .catch((err) => {
            if(err.response.status === 401){
//                this.error = err.response.data.message

                    reject('Validation error')

            }
            else

                    reject('Something went wrong')
        })
})
    }

You broke the promise chain by not returning the promise that is returned by axios in your login method (and the inner call to axios.get(apiUrl + 'user/log',

return axios.post(authUrl...

Return values from then handlers of Promises are chained , see this example:

 // a here points to a promise that will resolve to "Just the 2 of us" const a = Promise.resolve(1) .then(val => val + val) .then(val => `Just the ${val} of us`); a.then(val => console.log(val)) 

In your login function, you have returned a promise within axios post call which is async in nature. Your function which should return a promise is not returning anything. So you can refer the code below.

login() {
  let promise = new Promise(function(resolve, reject) {

  // your post call (dummy data) 
  axios.post(authUrl, postData).then(response => {
        if(response.status === 200) {
           resolve('foo');
        } else {
           reject('Login successful');
        }
  });

  return promise;
}

Hope this helps.

You can use async/await pattern.

async login(user) {
  const postData = {
    grant_type: 'password',
    username: user.email,
    password: user.password,
    client_id: clientId,
    client_secret: clientSecret,
    scope: '',
    provider: provider
  };

  const authUser = {};
  try {
    const postResponse = await axios.post(authUrl, postData);
    if (postResponse.status === 200) {
      authUser.access_token = response.data.access_token;
      authUser.refresh_token = response.data.refresh_token;
      const response = await axios.get(apiUrl + 'user/log', {headers: getHeader()});
      if (response.status === 200) {
        authUser.email = response.data.email;
        authUser.first_name = response.data.first_name;
        authUser.last_name = response.data.last_name;
        authUser.userRole = response.data.role;
        store.commit('save', authUser);
        return 'Login successful';
      }
    }

    return 'Validation error';
  }  
  catch(err) {
    if (err.response.status === 401){
      return 'Validation error';
    }
    return 'Something went wrong';
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM