2017-05-30 17 views
0

我是JavaScript新手,並且存在異步行爲問題。我正在嘗試讀取React操作中的文件。重要的部分是這樣的:在React動作中讀取文件

if(file){ 
    const reader = new FileReader(); 
    reader.readAsDataURL(inquiryFile); 
    reader.onload = function() { 
     body = JSON.stringify({ 
      fileToUpload: reader.result, 
     }); 
     return dispatch(basicRequest(body)); 
    }; 
    reader.onerror = function(error) { 
     console.error('Error uploadingFile: ', error); 
    }; 
} 
else{ 
    return dispatch(basicRequest()); 
} 

的組件,它負責調用這個動作需要根據成功或錯誤結果派遣另一個動作。

return submitFileAction(masterId, data).then((result) => { 
    if (!result.error) { 
     console.log('success'); 
    } else { 
     console.log('error'); 
    } 
}); 

問題是,返回'then part'的結果未定義,filereader.onload在我得到錯誤後調用。 我想問一下如何等待filereader的結果。

謝謝。

回答

0

您可能想要將FileReader包裝到Promise中。

return submitFileAction(masterId, data).then((result) => { 
    console.log('success'); 
}).catch((error) => { 
    console.log('error'); 
}); 

這假設調度()也返回一個承諾:爲

if (file) { 
    return new Promise(function(resolve, reject){ 
    ... 
    reader.onload = function(){ 
     ... 
     resolve(dispatch(basicRequest(body))); 
    }; 
    reader.onerror = function(error) { reject(error); }; 
    }); 
} 

錯誤將被處理。