我怎样才能在React Native中使用Promise异步工作?

时间:2017-12-30 14:36:22

标签: asynchronous react-native promise

在React Native项目中,我使用Promise编写了这个函数,以异步方式完成工作;

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 个答案:

答案 0 :(得分:1)

JavaScript的异步行为仅与IO阻止功能相关。这意味着,事件循环不是等待IO功能,而是继续运行。

看到JS是单线程的,CPU限制计算会占用线程,并且无法异步完成。

然后,你唯一的办法是创建一个native module,它将在不同的线程中为你做计算,然后在完成后调用JS回调。