Play Ground

[Vue.js] promise 사용하기 본문

Programming/Vue.js

[Vue.js] promise 사용하기

haeru 2018. 9. 20. 10:32

promise를 사용하여 api콜하는 부분을 디자인해주었음

mixin의 promise부분을 살리고 

vm.promise(function)와 같이 사용하면 될듯

then 안에서 promise가 리턴되어야 그 결과값을 바탕으로 다음 then으로 넘어감



mixin.js

export default { methods: { promise: function(func){ //프로미스 만들기 return new Promise(function(resolve, reject){ resolve(func()) }) }, call: function(action) { var vm = this var successResult vm.promise(function(){ if (action.confirmMsg !== undefined) return vm.$confirm({ content: action.confirmMsg }) }) .then(() => { return action.run() }) .then(function(result) { successResult = result if (action.successMsg !== undefined){ return vm.$alert({ content: action.successMsg }) } }) .then(() => action.success(successResult)) .catch(function(error){ vm.errorAlert(error, action.errorTypeHandler) }) } }

main.js
import Vue from 'vue'
import myCall from './services/Call.js'

Vue.prototype.$call = myCall
test.vue

<template> ... </template> <script> import mixins from '../mixins/mixins.js' export default {     name: 'test',     mixins: [mixins],     methods: {         submit: function() {             var vm = this             if((vm.userId == '') || vm.userPw == '') return             var data = {                 userId : vm.userId, userPw : vm.userPw             }             var action = { run : function() {     return vm.$call.login(vm.userId, vm.userPw)                 },                 success : function(result) {                     localStorage.setItem('token', result.data.token)     localStorage.setItem('emailId', result.data.emailId)     document.location.href = "/"                 }             }             vm.call(action)         }     } }