async,await
11824 단어 자바 script
특징.
let syml = Symbol('aaa')
// console.log(syml)
let json = {
'a': 'apple',
'b': 'banana',
[syml]: 'other'
}
// console.log(json[syml])
for(let key in json){
console.log(key)
}
promise
특징.
으로 그 안에 어떤 미래 에 끝 날 수 있 는 사건(보통
)의 결과 가 보존 되 어 있다.
으로
이 가능 하 다.pending
(진행 중),fulfilled
(성공)과 rejected
(실패)입 니 다.비동기 작업 의 결과 만 현재 어떤 상태 인지 결정 할 수 있 고 다른 작업 도 이 상 태 를 바 꿀 수 없습니다.프로 미스 라 는 이름 의 유래 이기 도 하 다.영어 로'약속'이라는 뜻 으로 다른 수단 으로 는 바 꿀 수 없다 는 뜻 이다.pending
에서 fulfilled
으로,pending
에서 rejected
으로 바 뀔 수 있다.async,await
특징.
개 Promise
(한 방법 을 비동기 로 바 꾸 는 방법).return
은 then
방법
이 될 것 입 니 다.async
은 방법 을 변이 시 키 는 것 입 니 다.await
은 비동기 방법 이 실 행 될 때 까지 기다 리 는 것 입 니 다.비동기 방법 중의 데 이 터 를 얻 을 수 있 지만 비동기 방법 에서 사용 해 야 합 니 다.그리고 기능 을 막 을 수 있 습 니 다.비동기 로 전환 할 수 있 습 니 다*await 는 async 방법 에서 사용 해 야 합 니 다.예 1: async function gen(){
//return
// catch
// throw new Error('error')
return ' ';
}
gen().then(res =>{
console.log(res)
}).catch(e=>{
console.log(e)
})
예 2:
let p = new Promise((resolve, reject)=>{
resolve('success')
})
async function gen(){
// await promise promise
// promise
let params = await p
// await ,
console.log(params) //success
//await then resolve reject
return params;
}
gen().then(res =>{
console.log(res)
}).catch(e=>{
console.log(e)
})
generator
특징.
예 1:
function * gen(){
yield ' '
yield ' '
return ` `
}
let g1 = gen();
//
// console.log(g1.next()) //{ value: ' ', done: false } false
// console.log(g1.next()) // { value: ' ', done: false }
// console.log(g1.next()) // { value: ' ', done: true }
// for of return
// for(let val of g1) {
// console.log(val)
// }
//
// let [a, b] = gen()
// console.log(a)
// console.log(b)
//
// yield
// let [...a] = gen()
// console.log(a) //[ ' ', ' ' ]
// console.log(Array.from(gen()))//[ ' ', ' ' ]
예 2:
const axios = require('axios')
function * gen(username){
let name ;
name = yield username
yield axios.get(`https://api.github.com/users/${name}`) // name
}
let g1 = gen('nianxiongdi')
let username = g1.next().value
// console.log(g1) { value: 'nianxiongdi', done: false }
g1.next(username).value.then(resolve => {
console.log(resolve.data.login)
}).catch((e)=>{
console.log(e)
})
// console.log( g1.next() )
async,await,promise 사용 예
1.async/await 함수
const fetch = require('node-fetch')
function getZhihuColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
fetch(url)
.then(response => response.json()) // json
.then(data => {
// console.log(data)
console.log("DES:" + `${data.description}`)
console.log("INTRO:" + `${data.intro}`)
})
}
getZhihuColumn('feweekly')
2.async 함 수 를 promischiain 에 사용
const fetch = require('node-fetch')
//
// , async await
// async promise promise
async function getZhihuColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
const response = await fetch(url) //
// const data = await response.json()
// return data;
//
return await response.json();
}
getZhihuColumn('feweekly')
.then(data =>{
console.log(`NAME: ${data.description}`)
console.log("INTRO:" + `${data.intro}`)
})
3.임의의 종류의 함 수 를 async 스타일 로 변환
const fetch = require('node-fetch')
/*
async
*/
//
//
const getZhihuColumn = async (id) => {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
const response = await fetch(url) //
// const data = await response.json()
// return data;
//
return await response.json();
}
// async , , async
(async () => {
const data = await getZhihuColumn('feweekly');
console.log(`NAME: ${data.description}`);
console.log("INTRO:" + `${data.intro}`);
})();
const fetch = require('node-fetch')
/*
async
*/
class APIClent {
async getColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
const response = await fetch(url) //
return await response.json();
}
}
// async , , async
(async () => {
const client = new APIClent();
const data = await client.getColumn('feweekly'); // await
console.log(`NAME: ${data.description}`);
console.log("INTRO:" + `${data.intro}`);
})();
4.async 처리 오류
const fetch = require('node-fetch')
/*
async
*/
//
async function getZhihuColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
const response = await fetch(url) //
//
if(response.status !== 200){
throw new Error(response.statusText)
}
return await response.json();
}
// feweekly123
const showColumnInfo = async (id) =>{
try {
const data = await getZhihuColumn(id)
console.log(`NAME: ${data.description}`)
console.log("INTRO:" + `${data.intro}`)
} catch (error) {
console.log(error)
}
}
showColumnInfo('feweekly123')
/*
, catch
Error: Not Found
at getZhihuColumn (/home/nianxiongdi/Development/nodejs/es6/async/demo8.js:16:15)
at process._tickCallback (internal/process/next_tick.js:68:7)
*/
5.여러 await 작업 의 병렬 직렬 을 정확하게 처리 합 니 다.
const fetch = require('node-fetch')
/*
await
*/
//
async function getZhihuColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
const response = await fetch(url) //
//
if(response.status !== 200){
throw new Error(response.statusText)
}
return await response.json();
}
// feweekly123
const showColumnInfo = async () =>{
try {
//
// const feweekly = await getZhihuColumn('feweekly')
// const toolingtips = await getZhihuColumn('toolingtips')
//
const feweeklyPromise = getZhihuColumn('feweekly')
const toolingtipsPromise = getZhihuColumn('toolingtips')
const feweekly = await feweeklyPromise;
const toolingtips =await toolingtipsPromise;
console.log(`NAME: ${feweekly.description}`)
console.log("INTRO:" + `${feweekly.intro}`)
console.log(`NAME: ${toolingtips.description}`)
console.log("INTRO:" + `${toolingtips.intro}`)
} catch (error) {
console.log(error)
}
}
showColumnInfo('feweekly123')
6.promise.all()을 사용 하여 여러 await 작업 을 병행 합 니 다.
const fetch = require('node-fetch')
/*
promise.all() await
*/
//
async function getZhihuColumn(id) {
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
const response = await fetch(url) //
//
if(response.status !== 200){
throw new Error(response.statusText)
}
return await response.json();
}
// feweekly123
const showColumnInfo = async () =>{
try {
//
//all() promise await
const [feweekly, toolingtips ] = await Promise.all([
getZhihuColumn('feweekly'),
getZhihuColumn('toolingtips')
])
console.log(`NAME: ${feweekly.description}`)
console.log("INTRO:" + `${feweekly.intro}`)
console.log(`NAME: ${toolingtips.description}`)
console.log("INTRO:" + `${toolingtips.intro}`)
} catch (error) {
console.log(error)
}
}
showColumnInfo('feweekly123')
7.await 와 임의의 호 환.then()코드 를 결합
const bluebird = require('bluebird')
/**
* await .then()
*/
async function main(){
// const number = await 890;
/**
* await promise promise
*
* await Promise.resolve(890);
*/
// console.log(number)
await bluebird.delay(2000) // 2
}
main()
8.for 순환 에서 await 올 바 르 게 사용 하기
const bluebird = require('bluebird')
const fetch = require('node-fetch')
/**
* for await
*/
async function getZhihuColumn(id) {
// await bluebird.delay(1000);
const url = `https://zhuanlan.zhihu.com/api/columns/${id}`
const response = await fetch(url) //
return await response.json();
}
const showColumnInfo = async () =>{
try {
console.time('showColumnInfo') //
const names = ['feweekly', 'toolingtips']
/*
// 1
for(const name of names) {
const data = await getZhihuColumn(name)
console.log(`NAME: ${data.description}`)
console.log("INTRO:" + `${data.intro}`)
}
*/
// 2
const promises = names.map(x => getZhihuColumn(x));
for(const promise of promises){
const data = await promise
console.log(`NAME: ${data.description}`)
console.log("INTRO:" + `${data.intro}`)
}
console.timeEnd('showColumnInfo') //
} catch (error) {
console.log(error)
}
}
showColumnInfo()
수식 기
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Thymeleaf 의 일반 양식 제출 과 AJAX 제출텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.