使用Promises的异步POST请求

时间:2016-01-04 18:42:42

标签: javascript asynchronous promise form-data

我正在构建一个简单的上传器,而且我之前已经构建了很多,但没有使用promises,而且我遇到了问题。当我致电我的承诺时,我需要绑定我上传的文件"在下面的代码中说一个表单数据对象(data.append('xls', e.dataTransfer.files[0]),但是我不能再访问e事件,因此我无法访问它并将其绑定到表单data对象。

错误 - Uncaught (in promise) ReferenceError: e is not defined

<!DOCTYPE html>
<html>
<head>
    <script>
        //HELPER FUNCTION
        events = (o,type,handle)=>o.addEventListener(type,handle);
        listen = {
            drag: ['dragenter','dragover','drop','dragleave'],
            async: ['readystatechange','loadstart','progress','abort','error','load','timeout','loadend']
        };

        //PROMISES
        executor = {
            upload: (resolve,reject) =>{
                var data = new FormData();
                var client = new XMLHttpRequest();
                for(prop of listen.async){ events(client, prop, callback.upload[prop]);}

                //THIS IS WHERE MY PROBLEM LIES         
                data.append('xls', e.dataTransfer.files[0]);  
                client.addEventListener("load", callback.upload);
                client.open("POST", "/core/upload.php");
                client.send(data);
            }
        };

        //PROMISE CALLBACKS
        resolve = (value)=> console.log(value);
        reject = (reason)=> console.log(reason);    

        //EVENT HANDLES
        handles = {
            upload: {
                dragenter: (e)=> e.target.classList.remove('emboss'),
                dragover: (e)=> e.preventDefault(),
                drop: (e)=> {
                    e.preventDefault();
                    var p = new Promise(executor.upload);
                    console.log(p);
                },
                dragleave: (e)=> e.target.classList.add('emboss')   
            }
        };

        //ASYNC CALLBACKS
        callback = {
            upload: {
                readystatechange: (e)=> console.log(e.target.readyState),
                loadstart: (e)=> console.log('loadstart'),
                progress: (e)=> console.log('progress'),
                abort: (e)=> console.log('abort'),
                error: (e)=> console.log('error'),
                load: (e)=> console.log('load'),
                timeout: (e)=> console.log('timeout'),
                loadend: (e)=> console.log('loadend')
            }   
        };

        //INITIALIZATION
        init=()=>{
            var dropbox = document.getElementById('dropbox');
            for(prop of listen.drag){ events(dropbox, prop, handles.upload[prop]);}
        };  

        events(document,'DOMContentLoaded', init);
    </script>
</head>
<body>
    <div id='dropbox' class='fa fa-file-excel-o fa-4x emboss'></div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

基本问题是将从事件对象获取的参数传递给Promise的执行函数,注意Promise构造函数将执行函数称为同步

一种方法可能是创建一个执行器工厂函数,该函数将参数保存在闭包中,但是当存储文件参数值而执行者可以访问它时,这可能是过度的,应该同样有效。 例如,设置上传功能对象的属性,如:

executor = {
    upload: (resolve,reject) =>{
            var data = new FormData();
            var client = new XMLHttpRequest();
            for(prop of listen.async){ events(client, prop, callback.upload[prop]);}

            data.append('xls', executor.upload.files);
            ....  // etc 

并在创建承诺之前设置参数

. . .
executor.upload.files = e.dataTransfer.files[0]`;
var p = new Promise(executor.upload);
. . .