promise() 在 AWS lambda 中执行此操作。
我想在文件存储到 s3 后立即发送信号。我想知道 .promise() 在这里做什么。 (--s3.putObject({}).promise()--)
在 s3 存储上看到文件时,几乎在相同的时间点观察到 fetch(send_to_this_url) 的时间戳。基于此,promise() 并不是异步操作的。我这里有什么问题吗?
前几行中的第二行,当响应正常时返回响应。但是,如果它早点返回,文件就不会存储在 s3 中,但它已经存储在 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);
最佳答案
AWS JavaScript SDK 代码中的 .promise()
表示一种将基于回调的 API 转换为返回 Promise 的 API 的方法。
这允许您await
它,或者像任何其他promise一样调用.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);
关于javascript - Nodejs Lambda,.promise() 的用途是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59401917/