传递(object.function)作为参数

时间:2016-01-04 22:21:37

标签: javascript methods promise ecmascript-6 es6-promise

我正在使用Promises构建一个简单的拖放上传器但是当我尝试传递一个方法(object.function)作为promise的回调函数的参数resolve /时,我得到一个Uncaught SyntaxError: Unexpected token .拒绝。

我希望将我的承诺回调组织为resolvereject对象下方的方法,因此在上传的情况下,它将是resolve.uploadreject.upload,以及例如,如果我有一个签署承诺说用户身份验证,那么它将是ie。 resolve.signinreject.signin

当前的promise模式是链接then(),catch(),reject(),resolve()这是一个可怕的编程模式,如果你使用套接字和链2+异步调用代码变得难以管理你嵌套越来越多的匿名函数也称为pyramid of doom pattern,为了避免这种模式,我正在使用另一个我用过异步调用的无数次,因为我在下面的代码中设置了异步事件听众client.addEventListener(prop, callback.upload[prop]);并在单独的对象callback.upload.event中处理它们。

以同样的方式处理异步请求的回调响应,我试图实现promises以避免在如此长的无法管理的函数中链接/嵌套5-10异步请求,但是传递方法(object.function)对于promises function(resolve.upload,reject.upload)的回调函数似乎不起作用,但是我传递了一个全局函数(函数),即resolvereject它会正常工作,但这是不好,因为它会混淆全局命名空间,这就是我试图传递object.method的原因。

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="styles/upload.css"> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
    <script>
        //EVENT LISTENERS
        var listen = {
            drag: ['dragenter','dragover','drop','dragleave'],
            async: ['readystatechange','loadstart','progress','abort','error','load','timeout','loadend']
        };
        //PROMISES
       var executor = {
            //THIS IS WHERE MY PROBLEM LIES
            upload: function(resolve.upload,reject.upload){
                var data = new FormData();
                var client = new XMLHttpRequest();
                data.append('xls', executor.upload.files); 
                for(prop of listen.async){ 
                    client.addEventListener(prop, callback.upload[prop]);
                }
                client.open("POST", "/core/upload.php");
                client.send(data);
            }
        };
        //PROMISES HANDLERS
        var resolve = {
            upload: function(value){
                 console.log(value);
            }
        };
        var reject = {
             upload: function(reason){
                 console.log(reason);
             }
        };
        //USER HANDLERS
        var handles = {
            upload: {
                dragenter: function(e){
                    e.target.classList.remove('emboss');
                }
                dragover: function(e){
                     e.preventDefault();
                }
                drop: function(e){
                    e.preventDefault();
                    executor.upload.files = e.dataTransfer.files[0];
                    //CREATE PROMISE
                    var p = new Promise(executor.upload);
                    console.log(p);
                    //CHECK PROMISE STATUS, EVERY 3 SECS
                    setInterval(function(){
                        console.log(p);
                    }, 3000);
                }
                dragleave: function(e){
                     e.target.classList.add('emboss');
                }
            }
        };

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

        //INITIALIZATION
        function init(){
            var dropbox = document.getElementById('dropbox');
            for(prop of listen.drag){ 
                dropbox.addEventListener(prop, handles.upload[prop]);}
            };
        //CALL INIT
        document.addEventListener('DOMContentLoaded', init);
    </script>
    </head>
    <body>
        <div id="dropbox" class="fa fa-file-excel-o fa-4x emboss"></div>
    </body>
</html>

2 个答案:

答案 0 :(得分:2)

您无法将自己的回调传递给传递给Promise构造函数的函数。您可以做的是在后续链中注册回调,例如:

var p = new Promise(executor.upload).then(resolve.upload, reject.upload);

然而,为了使它有用,execute.upload函数必须实际根据resolve对象的作用调用传递的rejectXMLHttpRequest参数:

executor.upload = (resolve, reject) => {
    var client = new XMLHttpRequest();

    client.addEventListener('readystatechange', (e) => {
        // call `resolve` or `reject` as appropriate
    });

    // then register any more specific handlers
    for (prop of listen.async){ 
        client.addEventListener(prop, callback.upload[prop]);
    }

    client.open("POST", "/core/upload.php");
    client.send(data);
}

在Promise构造函数的回调中调用resolve()reject() 的操作最终会导致向{{1}注册的处理程序被叫。

答案 1 :(得分:1)

在&#34; fatarrow&#34;语法:

(param1, param2) => { thing to be returned }

左侧的parens中的名称是{ thing to be returned }部分的本地名称。事实上,除了这个&#34;的差异,关于所有的fatarrow数量是一个语法简写。所以这两个函数定义基本相同:

blah: ( alpha, bravo ) => alpha + ", " + bravo
function blah ( alpha, bravo ) { return alpha + ", " + bravo; }

你想:

upload: ( resfunc, rejfunc ) => { ...etc... }

无论您在哪里进行CALL上传,都可以去:

upload(resolve.upload, reject.upload)

我也不确定你对诺言的使用。据我所知,回调是给你的,你可以打电话。就是这样的。

var promise = new Promise(
    function(resolve, reject) {
        img.onload = function() {
            ctx.drawImage(img, 300, 100);
            resolve();                          // done, tell the promise
        };
        img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==';
    }
);

然后你可以使用类似的东西:

promise.then ( function () { /* promise says it is done, do something */ } );