Promise vere e await: la coda dei microtask viene svuotata
Il difetto: Boa le Promise le ha, ma nessuno chiamava run_jobs(), quindi ogni .then restava in coda per sempre e la pagina non si aggiornava — senza un solo errore da leggere. - fetch restituisce una Promise costruita dal motore (new Promise + resolve/reject tenuti nella richiesta), non più un oggetto con un then finto - text() e json() restituiscono Promise anche loro, come nel browser: senza, "await r.text()" riceveva la stringa e chi si aspettava una Promise si rompeva - run_jobs() dopo ogni ingresso di JavaScript: script, eventi, timer, consegna delle risposte di fetch - il guscio desktop serve le fetch anche nel percorso senza finestra: con --aspetta l'attesa non serviva a niente e la pagina restava sulla scritta iniziale - 7 test nuovi (tests/promise.rs): then, await, fetch+text, fetch+json, catch, Promise.all, Promise accesa dentro un gestore di clic - aggiornato il test che si aspettava r.text() sincrona: codificava la vecchia semplificazione, non il comportamento giusto Verifica end-to-end su HTTP vero: una pagina con await fetch e await r.json() mostra "ricevuto: Mosaic (200)". Wikipedia, che usa async/await ovunque, si carica senza panic.
This commit is contained in:
1 parent
71f45d8967
commit
6a14853d0d
6 files changed
+241
-18
No files matched your search
+33
-16
@@ -172,8 +172,11 @@ function __timer_prossimo() {
|
||||
}
|
||||
|
||||
/* fetch: la richiesta si accoda, la esegue il guscio (che sa fare rete) e la
|
||||
risposta torna qui con __risposta(). Il corpo si legge in modo sincrono
|
||||
(`r.text()`), semplificazione dichiarata rispetto alle Promise. */
|
||||
risposta torna qui con __risposta(). È una Promise vera, costruita dal
|
||||
costruttore del motore: `then`, `catch`, `await` e `Promise.all` funzionano,
|
||||
purché la coda dei microtask venga svuotata dopo ogni evento — lo fa la parte
|
||||
Rust con `run_jobs`. `text()` e `json()` restituiscono Promise anche loro, come
|
||||
nel browser: senza, `await r.text()` darebbe la stringa e non una Promise. */
|
||||
var __richieste = [];
|
||||
var __prossima_richiesta = 1;
|
||||
|
||||
@@ -184,16 +187,13 @@ function fetch(url, opzioni) {
|
||||
id: id,
|
||||
url: String(url),
|
||||
metodo: opz.method ? String(opz.method).toUpperCase() : 'GET',
|
||||
corpo: (opz.body === undefined || opz.body === null) ? null : String(opz.body),
|
||||
callback: null,
|
||||
errore: null
|
||||
corpo: (opz.body === undefined || opz.body === null) ? null : String(opz.body)
|
||||
};
|
||||
__richieste.push(richiesta);
|
||||
var oggetto = {
|
||||
then: function (fn) { richiesta.callback = fn; return oggetto; },
|
||||
catch: function (fn) { richiesta.errore = fn; return oggetto; }
|
||||
};
|
||||
return oggetto;
|
||||
return new Promise(function (resolve, reject) {
|
||||
richiesta.resolve = resolve;
|
||||
richiesta.reject = reject;
|
||||
});
|
||||
}
|
||||
|
||||
function __richieste_pendenti() {
|
||||
@@ -214,18 +214,20 @@ function __risposta(id, stato, corpo) {
|
||||
var r = __richieste[i];
|
||||
__richieste.splice(i, 1);
|
||||
if (stato < 0) {
|
||||
if (r.errore) { try { r.errore({ message: 'richiesta fallita' }); } catch (e) { __log(String(e)); } }
|
||||
if (r.reject) { r.reject(new Error('richiesta fallita')); }
|
||||
return 1;
|
||||
}
|
||||
if (!r.callback) { return 0; }
|
||||
var risposta = {
|
||||
ok: stato >= 200 && stato < 300,
|
||||
status: stato,
|
||||
url: r.url,
|
||||
text: function () { return corpo; },
|
||||
json: function () { return JSON.parse(corpo); }
|
||||
headers: { get: function () { return null; }, has: function () { return false; } },
|
||||
text: function () { return Promise.resolve(corpo); },
|
||||
json: function () {
|
||||
return Promise.resolve(corpo).then(function (t) { return JSON.parse(t); });
|
||||
}
|
||||
};
|
||||
try { r.callback(risposta); } catch (e) { __log('errore nel gestore di fetch: ' + e); }
|
||||
if (r.resolve) { r.resolve(risposta); }
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -1392,6 +1394,9 @@ impl Macchina {
|
||||
if let Err(e) = self.ctx.eval(Source::from_bytes(codice.as_str())) {
|
||||
errori.push(format!("script #{}: {}", i + 1, e));
|
||||
}
|
||||
// le continuazioni delle Promise (then/await) sono microtask: senza
|
||||
// questo restano in coda per sempre e la pagina non si aggiorna
|
||||
self.ctx.run_jobs();
|
||||
}
|
||||
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
|
||||
applica(doc, ops);
|
||||
@@ -1410,6 +1415,9 @@ impl Macchina {
|
||||
if let Err(e) = self.ctx.eval(Source::from_bytes(codice.as_str())) {
|
||||
errori.push(format!("script #{}: {}", i + 1, e));
|
||||
}
|
||||
// le continuazioni delle Promise (then/await) sono microtask: senza
|
||||
// questo restano in coda per sempre e la pagina non si aggiorna
|
||||
self.ctx.run_jobs();
|
||||
}
|
||||
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
|
||||
applica(doc, ops);
|
||||
@@ -1451,6 +1459,8 @@ impl Macchina {
|
||||
}
|
||||
}
|
||||
}
|
||||
// il gestore può aver acceso una Promise: le sue continuazioni girano ora
|
||||
self.ctx.run_jobs();
|
||||
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
|
||||
applica(doc, ops);
|
||||
eseguiti
|
||||
@@ -1479,6 +1489,7 @@ impl Macchina {
|
||||
0
|
||||
}
|
||||
};
|
||||
self.ctx.run_jobs();
|
||||
if eseguiti > 0 {
|
||||
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
|
||||
applica(doc, ops);
|
||||
@@ -1537,6 +1548,8 @@ impl Macchina {
|
||||
0
|
||||
}
|
||||
};
|
||||
// la risposta sblocca `await fetch(...)`: le continuazioni girano adesso
|
||||
self.ctx.run_jobs();
|
||||
let ops = STATO.with(|s| std::mem::take(&mut s.borrow_mut().ops));
|
||||
applica(doc, ops);
|
||||
eseguiti
|
||||
@@ -2060,10 +2073,14 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn fetch_accoda_e_la_risposta_esegue_il_callback() {
|
||||
// `r.text()` restituisce una Promise, come nel browser: la catena è
|
||||
// annidata, e questo test difende proprio quello (prima era sincrona)
|
||||
let mut built = treebuilder::parse(
|
||||
"<div id=\"t\">vuoto</div><script>\
|
||||
fetch('/dati.json').then(function (r) {\
|
||||
document.getElementById('t').textContent = 'stato ' + r.status + ': ' + r.text();\
|
||||
return r.text().then(function (t) {\
|
||||
document.getElementById('t').textContent = 'stato ' + r.status + ': ' + t;\
|
||||
});\
|
||||
});</script>",
|
||||
);
|
||||
let mut macchina = Macchina::nuova().expect("interprete");
|
||||
|
||||
Reference in new issue
Block a user