/* 2023-04-26 */
https://www.sitepoint.com/community/t/best-way-to-use-if-else-in-a-promise-chain/414101/8
/* 2023-04-25 */
// https://stackoverflow.com/questions/24928846/get-return-value-from-settimeout
( (delay) => { return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(Math.floor(Math.random() * 2) ); /* returns a zero or a one BETTER WAY SEE SITEPOINT FORUM */
}, delay);
});
})(1500)
.then( (done) => { return ( ‘==>>’ + done )
})
.then( (last) => console.log(last) )
;
/* 2023-01-12a – async.await chaining */
const asyncFunction = (timeIn) => {
return new Promise( (resolve, reject) => {
setTimeout(() => {
resolve(++timeIn);
}, timeIn * 1000);
});
}
(async (value) => {
console.log(‘starting with: ‘, value);
const firstResult = await asyncFunction(value);
const secondResult = await asyncFunction(firstResult);
console.log(‘ending with:’, secondResult);
})(1);
/* 2023-01-12 – async-await chaining */
async function asyncCounterFunction(counter) { return ++counter; }
(async (initialData) => { const firstTime = await asyncCounterFunction(initialData); const secondTime = await asyncCounterFunction(firstTime); const thirdTime = await asyncCounterFunction(secondTime) console.info(await asyncCounterFunction(thirdTime)) console.log(‘Completion!’); })(1) async function testFunction(initialData) { const firstTime = await asyncCounterFunction(initialData); const secondTime = await asyncCounterFunction(firstTime); const thirdTime = await asyncCounterFunction(secondTime) console.info(await asyncCounterFunction(thirdTime)) console.log(‘Completion!’); } testFunction(1);async function asyncCounterFunction(counter) { try { return ++counter; } catch(e) { console.error(e) } }
/* 2023-01-10 – added async-await instead */
const myFunction = async (seconds) => { await setTimeout( () => { console.info(seconds, “done!”); }, seconds) } ; myFunction(2000) ;
/* one liner */
( async (seconds) => { await setTimeout( () => { console.info(seconds, “done!”); }, seconds) } )(2000)
/* old ugly way */
async function newFunction(seconds) { await setTimeout( () => { console.info(seconds, “done!”); }, seconds) } ; newFunction(2000) ;
==================================================================================
<<< leave this on top, fast & crude way to flatten out a promise! >>>
(async () => { try { let result = await feathersApp.logout(); console.log(‘the result is: ‘ + result) } catch (e) { console.log(e); } } ) () ;
(async () => let logoutResult = await feathersApp.logout(); console.log(logoutResult); })().catch(e => { console.log(e) });
===========================================================================================
2022-03-25:
const firstPromise = (promiseInput) => {
return new Promise( (resolve, reject) => { // long version
console.log(promiseInput);
let returnStuff = promiseInput + ‘ – parameter passed into first promise. ‘ ;
setTimeout( () => {
console.log (‘waiting a half-second, resolving: ‘ + returnStuff);
resolve (returnStuff);
},500 );
// we could use the “reject” function if this promise failed!
})
}
// shorter version per “windbeneathmywings”
const secondPromise = (promiseInput) => new Promise( (resolve, reject) => {
console.log(promiseInput);
let returnStuff = promiseInput + ‘ – parameter passed into second promise. ‘ ;
setTimeout( () => {
console.log (‘waiting a half-second, resolving: ‘ + returnStuff);
resolve (returnStuff);
},500 );
})
const thirdPromise = (promiseInput) => new Promise( (resolve, reject) => {
console.log(promiseInput);
let returnStuff = promiseInput + ‘ – parameter passed into third promise. ‘ ;
setTimeout( () => {
console.log (‘waiting a half-second, resolving: ‘ + returnStuff);
resolve (returnStuff);
},500 );
})
firstPromise(‘one’)
.then( value => { return secondPromise (value + ‘ two’) }) // long version
.then( value => thirdPromise (value + ‘ three’) ) // shorter version per “windbeneathmywings”
.then( value => console.log(’ FINAL result: ‘ + value) )
.catch( error => { console.log(’ ERROR! ‘ + error ) })
;
=================================================================================
// ======================================================
// ** 2021-09-14 10:47 AM return promise(dot)then example **
const promiseA = (parm) => {
return new Promise( (resolve, reject) => {
setTimeout( () => {
resolve(“promise-A “ + parm);
}, 1000 );
});
}
const promiseB = (parm) => {
return new Promise( (resolve, reject) => {
setTimeout( () => {
resolve(“promise-B “ + parm);
}, 2000 );
});
}
const promiseC = (parm) => {
return new Promise( (resolve, reject) => {
setTimeout( () => {
resolve(“promise-C “ + parm);
}, 3000 );
});
}
function getExample(initialParms) { /* notice Promise-dot-then-dot-catch usage, NOT async/await usage */ // locally scoped const results = {};
return promiseA(initialParms)
.then ( (resultA) => {
// add value to results object
results.a = resultA;
// pass result of this promise to next promise
return promiseB(resultA);
}
)
.then ( (resultB) => {
results.b = resultB;
return promiseC(resultB);
}
)
.then ( (resultC) => {
results.c = resultC;
// results object now contains all values from promise chain
return Promise.resolve(results);
}
)
.catch ( (error) => {
return Promise.reject(error);
}
)
;
}
let marksResults ; getExample(‘first parms entered’).then( (finalResults) => { marksResults = finalResults } ) ;
// =======================================================
// ** 2021-09-13 3:00 PM async/await example **
const promiseA = (parm) => { return new Promise((resolve, reject) => { setTimeout(resolve, 0500, ‘promise A ‘ + parm); }) };
const promiseB = (parm) => { return new Promise((resolve, reject) => { setTimeout(resolve, 0500, ‘promise B ‘ + parm); }) };
async function getExample(parm) {
/* notice async/await usage, not Promise-dot-then-dot-catch usage */
let resultA = await promiseA(parm);
console.log(‘first: ‘ + resultA);
// some processing
let resultB = await promiseB( parm + ‘-’ + resultA );
console.log(‘second: ‘ + resultB);
// more processing
return resultB // something using both resultA and resultB
}
let final ; getExample(‘123’).then ( (xx) => { final = xx ; } )
// =====================================================
// ** 2021-09-13 10am Promises.all example where parameters are not passed **
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
my own example of “Promises.all”:
const promise1 = new Promise((resolve, reject) => { setTimeout(resolve( ‘promise one’), 0500 ); }); // notice different way for parm!
const promise2 = new Promise((resolve, reject) => { setTimeout(resolve, 6000, ‘promise two’); });
const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 8000, ‘promise three’); });
Promise.all([promise1, promise2, promise3]) .then ((values) => { console.log(values); }) .finally((values) => { console.log(‘here!’); }) ;
// ================================================================================
Chained Promises:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(‘foo’);
}, 300);
});
myPromise .then(value => { return value + ‘ and bar’; }) .then(value => { return value + ‘ and bar again’; }) .then(value => { return value + ‘ and again’; }) .then(value => { return value + ‘ and again’; }) .then(value => { console.log(‘value: ‘ + value) }) .catch(err => { console.log(err) });
https://www.mariokandut.com/how-to-wait-for-multiple-promises-in-node-javascript/
How to use Promise.all
const all = Promise.all([
new Promise((resolve, reject) =>
setTimeout(() => resolve(1), 1000),
),
new Promise((resolve, reject) =>
setTimeout(() => resolve(2), 2000),
),
new Promise((resolve, reject) =>
setTimeout(() => resolve(3), 3000),
),
]).catch(err => console.log(‘Promise was rejected!’, err));
all.then(results => console.log(results)); // the output is: [1, 2, 3]
https://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain
A less harsh spin on “Mutable contextual state”
function getExample(){
//locally scoped
const results = {};
return promiseA(paramsA).then(function(resultA){
results.a = resultA;
return promiseB(paramsB);
}).then(function(resultB){
results.b = resultB;
return promiseC(paramsC);
}).then(function(resultC){
//Resolve with composite of all promises
return Promise.resolve(results.a + results.b + resultC);
}).catch(function(error){
return Promise.reject(error);
});
}