Your MDN reference was helpful. Thx.
If you run this, you should see
asynchronous output.
================================================================
asynchronous using "Promise"
const log = console.log;
//---------------------------------------
class PromiseLab {
play_promise_chain(start) {
//"then" returns a promise, so we can chain
const promise = new Promise((resolve, reject) => {
resolve(start);
});
promise.then((start) => {
log(`Value: "${start}" -- adding one`);
return start + 1;
}).then((start) => {
log(`Value: "${start}" -- adding two`);
return start + 2;
}).then((start) => {
log(`Value: "${start}" -- adding three`);
return start + 3;
}).catch((error) => {
if (error) log(error);
});
}
}
//---------------------------------------
const lab = new PromiseLab();
lab.play_promise_chain(100);
lab.play_promise_chain(200);
Output should be asynchronous something like:
Value: "100" -- adding one
Value: "200" -- adding one
Value: "101" -- adding two
Value: "201" -- adding two
Value: "103" -- adding three
Value: "203" -- adding three
================================================================
Synchronous using "MyPromise" (e.g. basic js code)
const log = console.log;
//---------------------------------------
class MyPromise {
value(value) { this.value = value; }
error(err) { this.error = err; }
constructor(twoArgFct) {
twoArgFct(
aValue => this.value(aValue),
anError => this.error(anError));
}
then(resultHandler) {
const result = resultHandler(this.value);
return new MyPromise((resolve, reject) => {
resolve(result);
});
}
catch(errorHandler) {
errorHandler(this.error());
}
}
//--------------------------------------
class MyPromiseLab {
play_promise_chain(start) {
//"then" returns a promise, so we can chain
const promise = new MyPromise((resolve, reject) => {
resolve(start);
});
promise.then((start) => {
log(`Value: "${start}" -- adding one`);
return start + 1;
}).then((start) => {
log(`Value: "${start}" -- adding two`);
return start + 2;
}).then((start) => {
log(`Value: "${start}" -- adding three`);
return start + 3;
}).catch((error) => {
if (error) log(error);
});
}
}
//---------------------------------------
const lab = new MyPromiseLab();
lab.play_promise_chain(100);
lab.play_promise_chain(200);
Output should be synchronous:
Value: "100" -- adding one
Value: "101" -- adding two
Value: "103" -- adding three
Value: "200" -- adding one
Value: "201" -- adding two
Value: "203" -- adding three