2017-12-30 23 views
1

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?!

Antwort

1

Das asynchrone Verhalten von JavaScript ist nur für IO-Blockierungsfunktionen relevant. Das heißt, anstatt auf eine IO-Funktion zu warten, läuft die Ereignisschleife weiter.

Da JS single threaded ist, nehmen CPU-gebundene Berechnungen den Thread auf und können nicht asynchron ausgeführt werden.

Sie können also nur eine native module erstellen, die die Berechnung in einem anderen Thread für Sie ausführt, und dann einen JS-Callback aufrufen, wenn es fertig ist.

+0

Hoppla! Das wusste ich leider nicht! – YUSMLE

+0

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

+0

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

Verwandte Themen