Skip to content

Instantly share code, notes, and snippets.

@tvolodimir
Last active May 25, 2018 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvolodimir/49d9a0d9dea717d15c53e47298194713 to your computer and use it in GitHub Desktop.
Save tvolodimir/49d9a0d9dea717d15c53e47298194713 to your computer and use it in GitHub Desktop.
#demo: promises/aysnc/callback js
// conditional promises chaining
function preTask(): Promise<void> {
console.log('pre task');
return Promise.resolve();
}
function task1(): Promise<void> {
console.log('task for type1');
return Promise.resolve();
}
function task2(): void {
console.log('task for type2');
}
function finalTask(): void {
console.log('final task');
}
function doJob(type: string): Promise<void> {
let promise: Promise<void> = Promise.resolve();
promise = promise.then(() => preTask());
switch (type) {
case "type1":
promise = promise.then(() => task1());
break;
case 'type2':
promise = promise.then(() => task2());
break;
case 'type3':
// do nothing
break;
default:
promise = promise.then(() => {
throw new Error('bad type')
});
}
return promise.then(() => finalTask());
}
// ->
async function doJob(type: string): Promise<void> {
await preTask();
switch (type) {
case "type1":
await task1();
break;
case 'type2':
await task2();
break;
case 'type3':
break;
default:
throw new Error('bad type');
}
await finalTask();
}
// foreachPromise
export function foreachPromise<T>(arr: T[], fn: (item: T, index?: number) => Promise<void>): Promise<void> {
let index = 0;
return new Promise<void>(function (resolve, reject) {
compile();
function compile() {
if (index < arr.length) {
fn(arr[index], index)
.then(() => {
index++;
compile();
})
.catch(error => reject(error));
}
else {
resolve();
}
}
});
}
const storage = {};
function fetchDataByItemId(itemId): Promise<void> {
return fetch('https://example.org/post',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({itemId})
})
.then(rawResp => rawResp.json())
.then(json => storage[itemId] = json);
}
function doJob() {
foreachPromise<string>(['1', '2', '3'], fetchDataByItemId)
.then(() => console.log('all done'))
.catch(err => console.error(err));
}
// ->
export async function foreachPromiseAsync<T>(arr: T[], fn: (item: T, index: number) => Promise<void>): Promise<void> {
for (let i = 0; i < arr.length; i++) {
await fn(arr[i], i);
}
}
async function fetchDataByItemId(itemId): Promise<void> {
const rawResp = await fetch('https://example.org/post',
{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({itemId})
});
storage[itemId] = await rawResp.json();
}
async function doJob() {
try {
await foreachPromise<string>(['1', '2', '3'], fetchDataByItemId);
console.log('all done');
}
catch (err) {
console.error(err);
}
}
function setLoadingVisibility(isVisible: boolean): void {
console.log('isVisible= ', isVisible);
}
function doPart1(): Promise<void> {
return Promise.resolve();
}
function doMainPart(): Promise<void> {
// return Promise.resolve();
return Promise.reject('ha-ha');
}
function showConfirmPopup(): Promise<boolean> {
return Promise.resolve(true);
}
function doSomeLoginProcessJob(): Promise<void> {
setLoadingVisibility(true);
return doPart1()
.then(() => {
return showConfirmPopup()
.then(isConfirmed => {
if (isConfirmed) {
return doMainPart();
}
})
})
.then(() => setLoadingVisibility(false))
.catch(err => {
setLoadingVisibility(false);
throw err;
});
}
// ->
async function doSomeLoginProcessJob(): Promise<void> {
setLoadingVisibility(true);
try {
await doPart1();
const isConfirmed = await showConfirmPopup();
if (isConfirmed) {
await doMainPart();
}
}
finally {
setLoadingVisibility(false);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment