# Promise 연습문제

Doozuu·2022년 11월 30일
0

Javascript

목록 보기
31/99
post-thumbnail

1. 이미지 로딩 성공시 특정 코드 실행

html

<img id="test" src="https://codingapple1.github.io/kona.jpg"> 

js

let img = document.getElementById('test');

var 실행 = new Promise(function(resolve,reject){
	img.addEventListener('load',function(){resolve()})
	img.addEventListener('error',function(){reject()})
})

실행.then(function(){
	console.log('성공')
}).catch(function(){
	console.log('실패')
})


2. Ajax 요청이 성공하면 코드 실행

var 프로미스 = new Promise(function(resolve,reject){
	$.ajax({
	type : 'GET',
    url : 'https://codingapple1.github.io/hello.txt '
}).done(function(인삿말){
	resolve(인삿말)
})
})

프로미스.then(function(인삿말){
	console.log(인삿말);
})

참고 : Ajax 사용법

jQurey로 Ajax 요청을 하려면 $.ajax 혹은 $.get 를 써야한다.(상단에 jQuery 설치 파일도 첨부되어 있어야 함.)

$.ajax({
  type : 'GET',
  url : 'URL 경로'
}).done(function(결과){
  console.log(결과);
});
$.get('URL 경로').done(function(결과){
  console.log(결과)
});


3. Promise chaining

var 프로미스 = new Promise(function(resolve,reject){
	$.ajax({
	type : 'GET',
    url : 'https://codingapple1.github.io/hello.txt '
}).done(function(인삿말){
	resolve(인삿말)
})
})

프로미스.then((인삿말)=>{
  console.log(인삿말);
  var 프로미스2 = new Promise(function(resolve,reject){
  $.get('https://codingapple1.github.io/hello2.txt').done(function(인삿말){
  resolve(인삿말)
	})
	});
  return 프로미스2;
}).then((인삿말)=>{
  console.log(인삿말);
})
profile
모든게 새롭고 재밌는 프론트엔드 새싹

0개의 댓글