【问题标题】:How I can do a job asynchronously using Promises in React Native?如何在 React Native 中使用 Promises 异步完成工作?
【发布时间】:2018-06-10 14:53:13
【问题描述】:

在一个 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 的方法有什么问题?!

【问题讨论】:

    标签: asynchronous react-native promise


    【解决方案1】:

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

    由于 JS 是单线程的,CPU 受限的计算占用线程,不能异步完成。

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

    【讨论】:

    • 糟糕!不幸的是,我不知道!
    • 为您创建一个native module 解决方案;我们的加密工作基于 JavaScript 库。这就是我们使用 React Native 的原因!
    • 虽然我完全了​​解您的来历,但有些事情与平台的工作方式有关。这不是灵丹妙药。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    相关资源
    最近更新 更多