Learn Intermediate JavaScript - Codecademy

Ari·2022년 7월 8일
0

WIT

목록 보기
1/2

Learn Intermediate JavaScript - Codecademy

Classes

Introduction to Classes

Constructor

  • 객체랑 비슷하게 생겼지만 가장 중요한 다른점은 constructor
  • JavaScript calls the constructor() method every time it creates a new instance of a class.

Instance

Methods

Method Calls

Inheritance

왜 super 키워드를 써줘야 하나 ?
https://ko.javascript.info/class-inheritance#ref-451

  • When a regular function is executed with new, it creates an empty object and assigns it to this.
  • But when a derived constructor runs, it doesn’t do this. It expects the parent constructor to do this job.

Static Methods

static 키워드로 선언된 function은 instance 에서는 접근할 수 없고 class이름으로만 접근 가능하다
https://ko.javascript.info/static-properties-methods

Review: Classes

class Apartment extends RentalUnit {
  constructor(address, costPerYear, numberOfBedrooms) {
    this._numberOfBedrooms = numberOfBedrooms;
    super(address, costPerYear);
  }

이 코드의 잘못된점? super 키워드가 this 이전에 먼저 호출되어야함

Modules

Promise

promiseChain

문제:

let link = state => {
  return new Promise(function(resolve, reject) {
    if (state) { 
      resolve('success'); 
    } else { 
      reject('error');
    }
  });
}
 
let promiseChain = link(true);
 
promiseChain
.then( data => {  
   console.log(data + " 1");
   return link(true);
})
.then( data => {
   console.log(data+ " 2");
   return link(true);
});
  • promise.then이 무엇이냐?
promise.then(
 function(result) { /* handle a successful result */ },
 function(error) { /* handle an error */ }
);

The first argument of .then is a function that runs when the promise is resolved and receives the result.

The second argument of .then is a function that runs when the promise is rejected and receives the error.

인데,

이 문제에선 .then안에 first argument (resolved되었을 때) 밖에 없고 그건 이것임

 data => {  
   console.log(data + " 1");
   return link(true);
}

주어진 코드에서 Promise정의? 를 보면

resolve('success'); 

로 되어있음

  1. 그래서 data 는 string 'success' 라서 console.log('success' + '1') 이 찍히고,
  2. link(true) 를 리턴하므로 statetrue 가 되어서 if (state) 내로 또 진입해서 console.log('success' + '2') 가 찍히게 된다

문제 2

function job() {
return new Promise(function(resolve, reject){ reject(); })
}

let promise = job();

promise 
.then(function(){
console.log("Success 1");
return promise;
})
.catch(function(){
console.log("Error 1");
return promise;
})
.then (function(){
console. log("success 2");
},function(){
console.log( "Error 2")
})

결과는 ? -

Error1 
Error2

.then (처음파라미터 , 두번째파라미터)
이렇게 썼을 때 처음파라미터가 resolve 되었을 때 실행되는 것이고
번째파라미터가 reject 되어씅ㄹ 때 되는 것인데
두번째줄엔 promise 정의에서 reject를 시켜주기 때문에 두번째 파라미터로 감
.catch 가 되면 그 뒤에있는 .then은 실행안되는줄 알았음............ (함수에서 return 해주면 그 함수 끝나잖아요? )- 이것처럼요.. 근데 아니었음

Async-Await

await 없이 async 쓰기 ? - 가능

As you assumed, if no await is present, the execution is not paused and your code will then be executed synchronously as normal.

async 없이 await 쓰기 ? - 불가능

에러뜸 ('async 없이는 await 쓰지 못합니다')

async function noAwait() {
 let value = myPromise();
 console.log(value);
}
 
async function yesAwait() {
 let value = await myPromise();
 console.log(value);
}

noAwait(); // Prints: Promise { <pending> }
yesAwait(); // Prints: Yay, I resolved!

In the first async function, noAwait(), we left off the await keyword before myPromise(). In the second, yesAwait(), we included it. The noAwait() function logs Promise { \ } to the console.

Without the await keyword, the function execution wasn’t paused. The console.log() on the following line was executed before the promise had resolved.

Remember that the await operator returns the resolved value of a promise. When used properly in yesAwait(), the variable value was assigned the resolved value of the myPromise() promise, whereas in noAwait(), value was assigned the promise object itself.

Handling Dependent Promises

function nativePromiseVersion() {
  returnsFirstPromise()
    .then((firstValue) => {
      console.log(firstValue);
      return returnsSecondPromise(firstValue);
    })
   .then((secondValue) => {
      console.log(secondValue);
    });
}

프로미스를 바꿔보자 ~!
바꾸면 이렇게 된다!

async function asyncPromiseVersion(){
 let firstValue = await returnsFirstPromise();
 console.log(firstValue)

 let secondValue = await returnsSecondPromise(firstValue);
 console.log(secondValue);
} 

Handling Independent Promises

async function waiting() {
 const firstValue = await firstAsyncThing();
 const secondValue = await secondAsyncThing();
 console.log(firstValue, secondValue);
}
 
async function concurrent() {
 const firstPromise = firstAsyncThing();
 const secondPromise = secondAsyncThing();
console.log(await firstPromise, await secondPromise);
}

제대로 이해한것이 맞다면 , 병렬적으로 실행하길 원하는 경우(두 프로미스가 서로에게 영향을 안주는 경우(예:첫 프로미스에서 리턴한 값을 두번째 프로미스에 전달하지 않아도 되는 경우)) 에는 concurrent() 처럼 작성을 하자.!

In the waiting() function, we pause our function until the first promise resolves, then we construct the second promise. Once that resolves, we print both resolved values to the console.

In our concurrent() function, both promises are constructed without using await. We then await each of their resolutions to print them to the console.

With our concurrent() function both promises’ asynchronous operations can be run simultaneously. If possible, we want to get started on each asynchronous operation as soon as possible! Within our async functions we should still take advantage of concurrency, the ability to perform asynchronous actions at the same time.

Note: if we have multiple truly independent promises that we would like to execute fully in parallel, we must use individual .then() functions and avoid halting our execution with await.

Await Promise.all()

그리고 위와 같은 경우에 Await Promise.all() 을 쓴다

We can pass an array of promises as the argument to Promise.all(), and it will return a single promise. This promise will resolve when all of the promises in the argument array have resolved.

quiz

async function myFunction() { 
  return 'hello world';
}
 
myFunction()
.then((resolvedValue) => {
  console.log(resolvedValue);
})

Q. What will this code print to the console?

A. hello world

(async 함수라서 promise를 리턴하는건 알겠으나 resolve 가 없기땜에 Promise{\} 이 아닐까 생각했는데 아니구나 .. 이것도 위의 질문처럼 첫번째 argument만 있어서 걍 무조건 resolve인 헬로월드가 리턴되나봄..)

myFunction() returns a promise. This promise will resolve to the return value of the async function: ‘hello world’. Inside the onFulfilled function passed into .then() we log the resolved value to the console. Therefore, ‘hello world’ will be printed to the console.

Requests

Get / Post 차이 ??

??

  • GET requests only request data from other websites, whereas
  • POST requests submit data to other sites.

ERROR HANDLING

Constructing an Error

console.log(Error('Your password is too weak.'));
// Prints: Error: Your password is too weak.

이거 두개는 같은것임

console.log(new Error('Your password is too weak.'));
// Prints: Error: Your password is too weak.
console.log('This message will be printed to the console.');

function throwError () {
  return notDefinedVar;
}

// Call throwError() below:
throwError();

console.log('Because of the error, this will not printed!');

이렇게 하면 프린트 안되지만

// Write your code below:
console.log(Error('User missing name'));


console.log('Will logging the error stop our program from running?'); //된다

아래는 된다 ..

The throw Keyword

Creating an error doesn’t cause our program to stop — remember, an error must be thrown for it to halt the program.

그래서 어떻게 하냐고? try catch 를 쓰자

try {
  throw Error('Practicing throwing');
} catch (e) {
  console.log(e);
}

console.log('printing? YES!')
profile
junior developer 🐤

0개의 댓글