Per utilizzare una promessa, devi chiamare una funzione che crea una promessa o devi crearne una tu stesso. Non è davvero descrivere ciò che problema si sta veramente cercando di risolvere, ma ecco come si creerebbe una promessa da soli:
function justTesting(input) {
return new Promise(function(resolve, reject) {
// some async operation here
setTimeout(function() {
// resolve the promise with some value
resolve(input + 10);
}, 500);
});
}
justTesting(29).then(function(val) {
// you access the value from the promise here
log(val);
});
// display output in snippet
function log(x) {
document.write(x);
}
Oppure, se si dispone già di una funzione che restituisce un promessa, è possibile utilizzare tale funzione e restituisce la sua promessa:
// function that returns a promise
function delay(t) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve();
}, t);
});
}
function justTesting(input) {
return delay(100).then(function() {
return input + 10;
});
}
justTesting(29).then(function(val) {
// you access the value from the promise here
log(val);
});
// display output in snippet
function log(x) {
document.write(x);
}
il valore di ritorno di una chiamata 'then()' è di nuovo una promessa, che racchiude il valore restituito. – Sirko
Si ha un errore di sintassi, non penso nemmeno che analizzi. Il test – djechlin
non è definito perché justTesting non restituisce nulla nell'esempio (non hai restituito). Aggiungi un reso e il test sarà definito come una promessa. –