【问题标题】:Meteor wrapAsync executes synchronously but never returnsMeteor wrapAsync 同步执行但从不返回
【发布时间】:2015-11-25 21:12:23
【问题描述】:

我正在尝试使用 wrapAsync 包装来自节点包的函数。

filepicker = new Filepicker('API Key') 
filepickerStatSync = Meteor.wrapAsync(filepicker.stat, filepicker)
result = filepickerStatSync(url);
console.log('after')

stat 函数如下。

一切似乎都正常...请求调用以正确的结果响应,调用最终回调,就我所知,整个事情同步执行/正确产生...但是同步调用永远不会返回并且console.log('after') 永远不会被命中。

我不认为我犯了与question 相同的错误,因为我的函数有一个回调作为最后一个参数。

我也不认为解决方案在这个question 中,因为包装函数确实以调用带有错误和结果的回调结束,这应该是 Meteor.wrapAsync 在签名中寻找的内容。

Filepicker.prototype.stat = function(url, options, callback) {
    callback = callback || function(){};
    if(!options) {
        options = {};
    }
    if(!url) {
        callback(new Error('Error: no url given'));
        return; 
    }
    request({
        method: 'GET',
        url: url+'/metadata?',
        form: {
            size: options.size || true,
            mimetype: options.mimetype || true,
            filename: options.filename || true,
            width: options.width || true,
            height: options.height || true,
            writeable: options.writeable || true,
            md5: options.md5 || true,
            path: options.path || true,
            container: options.container || true,
            security: options.security || {}
        }
    }, function(err, res, body) {
        console.log('err = '+err);
        console.log('res = '+res);
        console.log('body = '+body);
        if(err) {
            callback(err);
            return;
        }
        var returnJson;
        if(typeof(body)==='string'){
            try {
                returnJson = JSON.parse(body);
             } catch(e) {
                callback(new Error('Unknown response'), null, body);
                return;
             }
        } else {
            console.log('returnJSON');
            returnJson = body;
        }
        console.log('callbacked');
        callback(null, returnJson);
    });
};

【问题讨论】:

    标签: javascript node.js asynchronous meteor


    【解决方案1】:

    您要包装的函数接受三个参数,但您只提供两个:url,和(隐式)回调函数(我将其称为cb)。所以在内部,将执行的是Filepicker.prototype.stat(url, cb),即回调函数cb将被解释为options而不是callback,并且callback将被设置为一个空函数。所以 wrapAsync 的回调永远不会被调用,因为回调链被破坏了。

    这应该可行:

    result = filepickerStatSync(url, {});
    

    【讨论】:

    • 非常感谢。我的愚蠢疏忽。当系统允许我时,我会回来奖励赏金。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2016-09-09
    • 1970-01-01
    相关资源
    最近更新 更多