AWS如何在生成getSignedUrl之前等待headObject解析?

时间:2017-06-09 03:12:12

标签: node.js ecmascript-6 promise aws-lambda

我正在尝试在生成SignedUrl之前检查对象是否存在。但是,SignedUrl在headObject之前返回,生成指向不存在的对象的链接。

    var params = {
        Bucket: bucket,
        Key: path,
    };

    var signedURL = "none";
    s3.headObject(params, function (err, metadata) {
        if (err && err.code === 'NotFound')
            params.Key = 'no_image.png';

        params.Expires = 900;
        s3.getSignedUrl('getObject', params, function (err, url) {
            signedURL = url;
            if (err)
                console.log("Generation of Signed url failed");
            else
                console.log("Generated Signed url");
        });
    });
    console.log("Generating PreSigned Link ... Success");
    return resolve(signedURL);

以下代码看起来也不起作用:

var someVar = s3.headObject(params);
someVar.then(() ...

正如建议看了这篇文章 - Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference,它告诉我它为什么会发生但不是如何解决它。

这是我在回调中移动返回时尝试的新代码:

    s3.headObject(params, function (err, metadata) {
        params.Expires = 900;
        if (err && err.code === 'NotFound')
            params.Key = 'no_image.png';

        s3.getSignedUrl('getObject', params, function (err, url) {
            if (err)
                return resolve("none");
            else
                return resolve(url);
        });
    });

How to use promises with AWS headObject?

1 个答案:

答案 0 :(得分:0)

我在下面更新了您的代码。基本上,在完成通话之前,您正在解决承诺。

var params = {
  Bucket: bucket,
  Key: path,
};

var signedURL = "none";

s3.headObject(params, function (err, metadata) {
    params.Expires = 900;

    if (err && err.code === 'NotFound') {
        params.Key = 'no_image.png';
        resolve(signedURL);
    } else {
        s3.getSignedUrl('getObject', params, function (err, url) {
           signedURL = url;
           if (err) {
              console.log("Generation of Signed url failed");
              reject(url);
           } else {
             resolve(signedURL);
           }
        });
    }
});