【问题标题】:Issue with callback in using firebase and node.js使用 firebase 和 node.js 时的回调问题
【发布时间】:2018-07-30 14:08:31
【问题描述】:

我正在尝试获取 Cloud Storage 中图像的签名 URL 并将其返回给 node.js 服务器的 post 方法。

但返回的值总是未定义。请参考代码。

非常感谢任何帮助。

router.post('/', upload.single('file'), function(req, res) {
    var sign;
   var signedFinal = getUrl('cpu2.png',function(){
        console.log("hello" +signedFinal);
    });



function getUrl(image, callback){
        const file = bucket.file(image);
        const action = 'read';
        const expires = '03-09-2491';
        file.getSignedUrl({action:"read", expires}).then(function(url){
            sign=url[0];
            return url[0];
        }).catch(function (error) {
            {
                console.log(err);
            }
        });
    callback();
}

【问题讨论】:

    标签: node.js firebase google-cloud-storage firebase-storage


    【解决方案1】:

    使用异步函数元素/结果必须在回调中返回:

    https://blog.risingstack.com/node-hero-async-programming-in-node-js/

    function getUrl(image, callback){
            const file = bucket.file(image);
            const action = 'read';
            const expires = '03-09-2491';
            file.getSignedUrl({action:"read", expires}).then(function(url){
                sign=url[0];
                return callback(url[0]);
    
            }).catch(function (error) {
    
               return callback(null);
    
            });
    
    }
    
    router.post('/', upload.single('file'), function(req, res) {
    
        getUrl('cpu2.png',function(signedFinal){
            console.log("hello" +signedFinal);
    
            // do something here
            return res.status(200).json({img: signedFinal});
        });
    
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 2015-11-01
      • 2016-01-29
      • 2015-12-18
      • 2023-03-25
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多