首页 > 解决方案 > Nodejs Lambda,.promise() 的目的是什么?

问题描述

promise() 在 AWS lambda 中执行。

我想在文件存储在 s3 后立即发送信号。我想知道 .promise() 在这里做了什么。(--s3.putObject({}).promise()--)

当在 s3 存储上看到文件时,在几乎相同的时间点观察到 fetch(send_to_this_url) 的时间戳。基于此,promise() 不会异步操作。我这里有什么问题吗?

第二在前几行中,响应正常时返回响应。但是,如果它早点返回,文件就不会存储在 s3 中,但它已经存储了,所以我想知道第一个 if(response.ok) 的目的是什么。

请与我分享任何想法。!


fetch(url)
  .then((response) => {
    if (response.ok) {
      return response;
    }
    return Promise.reject(new Error(
          `Failed to fetch ${response.url}: ${response.status} ${response.statusText}`));
  })
  .then(response => response.buffer())
  .then((buffer) => {

      s3.putObject({
        ACL: "public-read",
        Bucket: process.env.BUCKET,
        Key: key,
        Body: buffer
      }).promise();   

      try{
        const send_to_this_url = "someurl?key=" + key;
        fetch(send_to_this_url);
      }catch(e){
        callback('error' + e.message);
      }

    }
  )
  .then(v => callback(null, v), callback);

标签: javascriptnode.jslambdapromiseaws-sdk-js

解决方案


AWS JavaScript SDK 代码中的.promise()代表一种将基于回调的 API 转换为返回承诺的方法。

这使您可以继续await使用它,或者.then像使用任何其他承诺一样调用。

你可以在你的代码中利用这一点,s3.putObject().promise()就像你对所有其他人所做的那样,将返回的 promise 链接起来:

fetch(url)
.then((response) => {
  // ...
})
.then(response => response.buffer())
// make this part of the promise chain
// use the promise returned when putting
// an object to s3
.then((buffer) => s3.putObject({
    ACL: "public-read",
    Bucket: process.env.BUCKET,
    Key: key,
    Body: buffer
  }).promise()
)
.then(() => {
  // this will run if all promises before it in the chain have resolved successfuly
  const send_to_this_url = "someurl?key=" + key;
  return fetch(send_to_this_url);
})
.then(resultFromFetchSendToThisUrl => {
  // ...
})
.catch(() => {
  // this will run if any promise in the chain above rejects
  // including the one from s3.putObject
})

也许使用 async-await 会使代码更具可读性:

const response = await fetch(url);

if (!response.ok) {
  throw new Error(
    `Failed to fetch ${response.url}: ${response.status} ${response.statusText}`
  )
}

const buffer = await response.buffer();

const result = await s3.putObject({
  ACL: "public-read",
  Bucket: process.env.BUCKET,
  Key: key,
  Body: buffer
}).promise()

const send_to_this_url = "someurl?key=" + key;
const resultFromFetchSendToThisUrl = await fetch(send_to_this_url);

推荐阅读