将 (object.function) 作为参数传递

Passing (object.function) as a parameter

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

我希望将我的承诺回调组织为 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.

以同样的方式我处理异步请求的回调响应,我正在尝试实现承诺以避免 chaining/nesting 5-10 异步请求在这么长的难以管理的函数中,但是传递一个方法( object.function) 对于承诺 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>

在"fatarrow"语法中:

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

左侧括号中的名称是 { thing to be returned } 部分的本地名称。事实上,除了"this"的不同,几乎所有的fatarrow都是语法上的shorthand。所以这两个函数定义基本一致:

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

你想要:

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

无论你在哪里调用上传,你都会去哪里:

upload(resolve.upload, reject.upload)

我也不确定你对 promises 的使用。据我了解,回调是给你的,你可以打电话。也就是这样的东西。

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 */ } );

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

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

然而,要使它有用,execute.upload 函数必须根据 XMLHttpRequest 对象的作用实际调用传递的 resolvereject 参数:

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() 的操作最终导致在 .then 注册的处理程序被打电话。