const test = async() =>{
const value = await Promise.resolve(1)
console.log(value)
}
test()
연산된 값을 반환해주지만 Promise객체이면 then메서드를 호출해 얻은 값을 반환
let value = await Promise
객체 혹은 값
await키워드는 async라는 이름의 함수 수정자가 있는 함수 몸통에서만 사용할 수 있다.
const test1 = async() =>{
await Promise 객체혹은 값
}
function과 화살표 함수로 함수 구현
export const test1 = async()=>{
let value = await 1
console.log(value)
value = await Promise.resolve(1)
console.log(value)
} //arrow
export async function test2(){
let value = await "Hello"
console.log(value)
value = await Promise.resolve("Hi")
console.log(value)
} //function
index.ts
import {test1, test2} from "./07/arrow"
test1()
test2()
//1
//Hello
//1
//Hi
import {test1, test2} from "./07/arrow"
test1().then(()=> test2())
//1
//1
//Hello
//Hi
const asyncReturn = async() =>{
return [1, 2, 3]
}
asyncReturn().then(value => console.log(value))
async함수에서 다음처럼 예외가 발생하면 프로그램이 비정상으로 종료됩니다.
const asyncException = async()=>{
throw new Error("err")
}
asyncException() //예외발생
예외가 발생해서 비정상적으로 종료되는 상황을 막으려면 catch메서드로 에러를 호출해야함
const asyncException = async()=>{
throw new Error("err")
}
asyncException().catch(err => console.log("error:", err.message))
만일 await 구문에서 Promise.reject값이 발생해도 비정상으로 종료됨(얘도 catch로 에러 받아내면 멈추지는 않고 실행)