티스토리 뷰

Skill/html js css

[javascript] promise

진열사랑 2020. 10. 2. 19:57

출처 : www.youtube.com/watch?v=JB_yU6Oe2eE&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=12

 

class UserStorage {
  loginUser (id, password) {
    return new Promise((resolve,reject)=>{
        setTimeout(() => {
            if (
                (id === 'ellie' && password === 'dream') ||
                (id === '' && password === '')
            ) {
              resolve(id);
            } else {
              reject(new Error('not found')); 
            }      
        }, 2000);
    });
  }
  getRoles (user) {
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            if (user === 'ellie') {
                console.log('user : ' + user);
                resolve({name:'ellie',role:'admin'});
            } else {
                reject(new Error('no access'));
            }
        }, 1000);
    })
  }
}

const userStorage = new UserStorage();
const id = prompt('enter user id');
const password = prompt('enter user password');

userStorage.loginUser(id,password)
  .then(user=>userStorage.getRoles(user))
  .then(user=>alert(`Hello ${user.name}! Your role is ${user.role}`))
  .catch(error=>console.log(error));


'use strict';

// 1. Producer
const promise = new Promise((resolve, reject)=>{ // promise를 생성하는 순간 넘겨지는 함수를 실행한다.
    console.log('doing something...'); 
    setTimeout(()=> {
        //resolve('ellie');
        reject(new Error('no network')); // reject가 호출되면 promise.catch가 반드시 있어야 에러가 나지 않는다. 그렇지 않으면 Uncaught 에러 발생된다.
    },2000)
});

// 2. Consummer
promise
  .then(value =>{ // promise가 정상적으로 실행된 후 resolve를 통해 value를 전달받아 실행한다.
    console.log(value);
  })
  .catch(error =>{
    console.log(error);
  })
  .finally(()=>{ // 성공하든 실패하든 상관없이 실행
    console.log('always excuted!!');
  });

// 3. Promise chaining
const fetchNumber = new Promise((resolve,reject)=>{
    setTimeout(()=> resolve(1), 1000);
});

fetchNumber
  .then( num => {
      console.log(num*2);
      return num * 2;
  })
  .then( num => num * 3 )
  .then( num => {
      return new Promise((resolve,reject)=>{
          setTimeout(()=>resolve(num - 1),1000);
      })
  })
  .then(num => console.log(num));

// 4. Error Handling
const getHen = ()=> 
  new Promise((resolve, reject)=>{
      setTimeout(()=>resolve('1'), 1000);
  });

const getEgg = hen =>
  new Promise((resolve,reject)=>{
      setTimeout(()=>resolve(`${hen} => 알`),1000);
  });
const cook = egg =>
  new Promise((resolve,reject)=>{
      setTimeout(()=>resolve(`${egg} => ??`), 1000);
  });

getHen()
  .then(hen=>getEgg(hen)) // .then(getEgg)
  .then(egg => cook(egg))
  .then(meal=>console.log(meal));

--------------

실적용.. 엇.. then이 순서대로 실행되는 줄 알았는데.. 아니네.. 어케된 것인지???

// 시설물 소블록설정 : 각 시설물의 위치가 어느 소블록에 해당하는지 GIS검색해서 해당 소블록 FTR_IDN으로 시설물의 BSM_IDN를 UPDATE
const setBsmidnFaciltyOne = function(p_tablename) {
	return new Promise(function(resolve, reject){
		var param = {};
		param["p_tablename"] = p_tablename[0];
		param["p_bsm_idn_opt"] = "NULL";
		param = JSON.stringify(param);
		$.ajax({
			type : "POST",
			url : apiUrlFront + "/setBsmidn",
			dataType : "json",
			data : param,
			contentType : "application/json;charset=UTF-8",
			success : function(data) {
				alert(p_tablename[1] + " : " + data.upd_cnt + "건 수정되었습니다.")
				resolve(data.upd_cnt);
			}
			,error : function(request, error) {
				reject(new Error("message: " + request.responseText + ", error:" + error));
			}
		});
	}	
)};
function setBsmidn() {
	setBsmidnFaciltyOne(["WTL_FLOW_PS","유량계"])
	.then(setBsmidnFaciltyOne(["WTL_GAIN_AS","취수장"]))
	.then(setBsmidnFaciltyOne(["WTL_META_PS","계량기  "]))
	.then(setBsmidnFaciltyOne(["WTL_PIPE_LS","상수관로"]))
	.then(setBsmidnFaciltyOne(["WTL_PRES_AS","가압장  "]))
	.then(setBsmidnFaciltyOne(["WTL_PRGA_PS","수압계  "]))
	.then(setBsmidnFaciltyOne(["WTL_PURI_AS","정수장  "]))
	.then(setBsmidnFaciltyOne(["WTL_SERV_AS","배수지  "]))
	.then(setBsmidnFaciltyOne(["WTL_SPLY_LS","급수관로"]))
	.then(setBsmidnFaciltyOne(["WTL_VALV_PS","밸브   "]))
	.catch(error =>{ alert(error) });
}

'Skill > html js css' 카테고리의 다른 글

[JQuery] ajax2 : 400 error발생  (0) 2020.10.13
[javascript] bind()사용법  (0) 2020.10.05
[javascript] 배열 함수들  (0) 2020.10.02
JQuery 첫 실행 문장들 비교  (0) 2020.09.28
[javascript] prototype  (0) 2020.09.24
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함