Hi all,
I’m trying to familiarize with the promise pattern, so I coded the following example.
I was able to understand the construct of the promises and how to get the messages from the promises, by resolve and reject.
I used many functions coded in public, some of these have setTimeout in order to explore the different timings.
OK, all works, but now I ask you an help on the second step.
I would like to get the output of the functions PROM, TIME, TIME2 and FINALE in the correct order waiting the end of each of them . Now it isn’t, obviously 'cause the different timings.
What’s the method, please ?
Thanks in advance
Mauro
The heart is:
Math.floor(Math.random() * 6) + 1
Here the main page, all the results you can see by console.log and outputs are not in order:
import {Random6,PROM,TIME, TIME2, FINALE} from 'public/function.js';
function uno(data) {console.log ('Great, threw ' + data + '.');}
function due(data) {console.log ('Oh no, threw ' + data + '.');}
$w.onReady(function () {
console.log('1 / start');
console.log("2 / batteria di funzioni ");
PROM().then(uno).catch(due);
TIME().then(uno).catch(due);
TIME2().then(uno).catch(due);
FINALE();
console.log('3 / end ')
});
and here the functions in public:
export function Random6(data) {
data = Math.floor(Math.random() * 6) + 1;
return data;
}
// la Promise che calcola una risposta (resolve,reject) in base al valore di Random6()
export function PROM() { return new Promise(
(resolve, reject) => {
var n=Random6();
console.log('funzione PROM: ');
if (n === 6) { resolve(n); } else { reject(n);}
});
}
// Un secondo modo di impostare una new Promise, introducendo un ritardo
export function TIME() { return new Promise(
function(resolve,reject) {
setTimeout( () => { console.log("Funzione TIME: "); resolve( PROM() ) } , 6000);
});
}
// Nuova Promise usa la funzione Random6(), ma non produce nessun reject, solo resolve
export function TIME2() { return new Promise(
function(resolve,reject) {
setTimeout( () => { console.log("Funzione TIME2: "); resolve(Random6()) } , 2000);
});
}
export function FINALE() {
console.log("Funzione FINALE");
}