In einem React Native-Projekt habe ich diese Funktion mit Promise
geschrieben, um einen Auftrag asynchron auszuführen;Wie kann ich einen Auftrag asynchron mit Promises in React Native ausführen?
function doEncryptionAsync(params) {
return new Promise(
function (resolve, reject) {
// Async code started
console.log('Promise started (Async code started)');
// The job that takes some times to process
var encrypted_value = new EncryptedValue(params);
if (true) {
resolveencrypted_value
}
else {
reject("Error while encrypting!");
}
}
)
}
Und ich nenne das in meiner Redux-Aktion;
export const encrypt = (params) => {
return (dispatch) => {
dispatch({
type: type.ENCRYPT
});
// Sync code started
console.log('Started (Sync code started)');
doEncryptionAsync(params)
.then((response) => {
// Async code terminated
console.log('Promise fulfilled (Async code terminated)');
encryptSuccess(dispatch, response);
})
.catch((error) => {
console.log(error);
encryptFail(dispatch);
});
// Sync code terminated
console.log('Promise made (Sync code terminated)');
}
}
Es funktioniert, aber nicht asynchron! Mein Haupt-Thread scheint blockiert zu sein, bis doEncryptionAsync()
zurückkehrt. Die Linie console.log('Promise made (Sync code terminated)')
läuft, aber nicht sofort!
Meine Ausgabe für Protokolle ist so;
// OUTPUT Simulation
Started (Sync code started) at time x
Promise started (Async code started) at time x
Promise made (Sync code terminated) at time (x + 2sec)
Promise fulfilled (Async code terminated) at time (x + 2sec)
Meine Frage ist, was mit meinem Ansatz falsch ist eine AsyncTask
zu implementieren?!
Hoppla! Das wusste ich leider nicht! – YUSMLE
Für Sie erstellen Sie eine 'native Modul'-Lösung; Unser Verschlüsselungsjob basiert auf einer JavaScript-Bibliothek. Aus diesem Grund verwenden wir React Native! – YUSMLE
Während ich völlig dahin komme, woher du kommst, gibt es Dinge, die nur mit der Funktionsweise der Plattform zu tun haben. Es ist keine Wunderwaffe. – Kraylog