【发布时间】: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