2017-08-24 87 views
1

我想它上傳到服務器(與火力地堡)之前調整圖像大小:如何讓代碼在下面的async/await函數中等待?

api.uploadPhoto = async (file = {}, field = {}) => { 
    const canvas = document.getElementById('canvas') 
    const img = document.createElement('img') 
    const reader = new FileReader() 
    let fileToUpload 

    reader.onload = function (e) { 
    img.src = e.target.result 
    pica.resize(img, canvas).then(result => { 
     fileToUpload = pica.toBlob(result, 'image/jpeg', 90)) 
    }) 
    } 
    reader.readAsDataURL(file) 

    // run the code below only when reader.onload has finished 

    return await imageUpload.toFirebase(fileToUpload, field) 
} 

的問題是,在imageUpload.toFirebase之前reader.onload運行。如何解決這個問題?

+0

你可能要考慮的承諾。在這裏你可以等待一個函數在開始下一個函數之前完成:https://spring.io/understanding/javascript-promises –

回答

2

移動上傳到回調...

api.uploadPhoto = async (file = {}, field = {}, callback) => { 
    const canvas = document.getElementById('canvas'); 
    const img = document.createElement('img'); 
    const reader = new FileReader(); 
    let fileToUpload; 

    reader.onload = function (e) { 
    img.src = e.target.result; 
    pica.resize(img, canvas).then(result => { 
     fileToUpload = pica.toBlob(result, 'image/jpeg', 90)); 
    }); 

    reader.readAsDataURL(file); 
    callback(await imageUpload.toFirebase(fileToUpload, field)); 

    } 
}; 
+0

我得到'index.js?2848:123 Uncaught(在承諾)TypeError:回調不是一個函數' – alex

+0

你提供了一個回調函數嗎?根據代碼示例(我稍微修改了您的輸入) – War

相關問題