2017-12-30 22 views
1

React Native 프로젝트에서 비동기 적으로 작업을 수행하려면 Promise을 사용하여이 함수를 작성했습니다.References Native의 Promises를 사용하여 비동기식으로 작업을 수행하는 방법은 무엇입니까?

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!"); 
     } 
    } 
) 
} 

그리고 나는이를 내 Redux 작업에서 호출합니다.

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)'); 
    } 
} 

작동하지만 비동기 적이 아닙니다. 내 주요 스레드는 doEncryptionAsync() 반환 될 때까지 차단 된 것으로 보입니다. 줄 console.log('Promise made (Sync code terminated)')가 실행되지만 즉시 실행되지는 않습니다!

내 로그 출력은 다음과 같습니다.

// 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) 

내 질문은 AsyncTask을 구현하기 위해 내 접근 잘못 무엇입니까?!

답변

1

JavaScript의 비동기 동작은 IO 차단 기능에만 관련이 있습니다. 즉, IO 함수를 기다리는 대신 이벤트 루프가 계속 실행됩니다.

JS가 단일 스레드 인 것으로 보는 것, CPU 경계 계산은 스레드를 사용하며 비동기 적으로 수행 할 수 없습니다.

유일한 방법은 다른 스레드에서 계산을 수행 할 native module을 작성한 다음 완료되면 JS 콜백을 호출하는 것입니다.

+0

죄송합니다. 나는 불행히도 그것을 몰랐다! – YUSMLE

+0

네이티브 모듈 솔루션을 만들려면; 우리의 암호화 작업은 JavaScript 라이브러리를 기반으로합니다. 우리가 React Native를 사용하는 이유입니다. – YUSMLE

+0

나는 당신이 어디에서 왔는지 완전히 알 수 있지만 플랫폼이 작동하는 방식과 관련이 있습니다. 은색 총알이 아니야. – Kraylog

관련 문제