1. async
2. await
3. async/await
1. Ajax call return data
2. webcam access request
3. image processing
WE GET IT
PROMISE ARE GREAT
PROMISE IS FOREVER
// callback
moveTo(50, 50, function() {
moveTo(20, 100, function() {
moveTo(100, 200, function() {
moveTo(2, 10, function() {});
});
});
});
// Promise
moveTo(50, 50)
.then(() => moveTo(20, 100))
.then(() => moveTo(100, 200))
.then(() => moveTo(2, 10));
// async/await
async function animate() {
await moveTo(50, 50);
await moveTo(20, 100);
await moveTo(100, 200);
await moveTo(2, 10);
}
function yesno(params) {
return axios("https://yesno.wtf/api");
}
async function qustion() {
try {
var qustion = await yesno("이번 발표가 성공할까요");
console.log(qustion.data.answer);
document.body.innerText = qustion.data.answer;
} catch (error) {
console.error(error);
}
}
qustion();
function myFunction() {
return "myFunction";
}
async function myAsync() {
return "myAsync";
}
console.log(myFunction());
console.log(myAsync());
async function myAsyncReject() {
throw "myAsyncReject";
}
myAsyncReject().catch(error => {
console.error(error);
});
async function myAsyncReject2() {
await Promise.reject(new Error("myAsyncReject2"));
}
myAsyncReject2().catch(error => {
console.error(error);
});
function myAwait() {
await "myAwait"
}
myAwait();
const makeRequest = () => {
return callAPromise()
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => {
throw new Error("oops");
})
}
makeRequest()
.catch(err => {
console.log(err);
// output
// Error: oops at callAPromise.then.then.then.then.then (index.js:8:13)
})
const makeRequest = async () => {
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
throw new Error("oops");
}
makeRequest()
.catch(err => {
console.log(err);
// output
// Error: oops at makeRequest (index.js:7:9)
})
const makeRequest = () => {
return getJSON()
.then(data => {
if (data.needsAnotherRequest) {
return makeAnotherRequest(data)
.then(moreData => {
console.log(moreData)
return moreData
})
} else {
console.log(data)
return data
}
})
}
const makeRequest = async () => {
const data = await getJSON()
if (data.needsAnotherRequest) {
const moreData = await makeAnotherRequest(data);
console.log(moreData)
return moreData
} else {
console.log(data)
return data
}
}
function loadData() {
return callAPromise()
.then(callback1)
.then(callback2)
.then(callback3)
.then(() => {
throw new Error("boom");
})
}
loadData()
.catch(function(e) {
console.log(err);
// Error: boom at callAPromise.then.then.then.then (index.js:8:13)
});
async function loadData() {
await callAPromise1()
await callAPromise2()
await callAPromise3()
await callAPromise4()
await callAPromise5()
throw new Error("boom");
}
loadData()
.catch(function(e) {
console.log(err);
// output
// Error: boom at loadData (index.js:7:9)
});