// 1. async functions always return a Promise
// 2. await will return resolved data of a promise, it can be a 'data or an 'error'.
// An async function: getDataPromise()
const getDataPromise = (num) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
typeof num === 'number' ? resolve(num * 2) : reject("Number must be provided")
}, 2000)
})
}
// 1. Call getDataPromise() directly within another funcion
const processData1 = () => {
getDataPromise(2).then(data => {
result = data;
console.log('Data1: ' + data);
}).catch(err => {
console.log("Error1: " + err)
})
}
processData1();
// 2. Return getDataPromise() then call it outside of a function.
const processData2 = () => {
return getDataPromise(2);
}
processData2().then(data => {
console.log('Data2: ' + data);
}).catch(err => {
console.log("Error2: " + err)
});
// 3. Call getDataPromise() with await in a async function
const processData3 = async () => {
// result can be the 'data' or the 'error'
const result = await getDataPromise('2');
return result;
}
processData3().then(data => {
console.log('Data3: ' + data);
}).catch(err => {
console.log('Error3: ' + err);
});
/////////////////////////////////////////////////////////////////////////////
// NOTE: await won’t work in the top-level code. But we can use it like this
/////////////////////////////////////////////////////////////////////////////
(async () => {
let response = await fetch('/article/promise-chaining/user.json');
let user = await response.json();
...
})();
/////////////////////////////////////////////////////////////////////////////
// NOTE: Thenable object also support async and await.
/////////////////////////////////////////////////////////////////////////////
class Thenable {
constructor(num) {
this.num = num;
}
then(resolve1, reject) {
console.log(resolve1);
// resolve with this.num*2 after 1000ms
setTimeout(() => resolve1(this.num * 2), 1000); // (*)
}
};
// 1. Call thenable object
// var obj = new Thenable(2);
// obj.then((data) => {
// console.log("resolve: " + data);
// }, err => {
// console.log("reject: " + err)
// })
// 2. Use async and await
async function f() {
// waits for 1 second, then result becomes 2
let result = await new Thenable(2);
console.log(result);
}
f();