Sun*_*Lee 1 javascript lambda node.js promise aws-sdk-js
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);
Run Code Online (Sandbox Code Playgroud)
AWS JavaScript SDK代码.promise()中的 代表一种将基于回调的 API 转换为返回 Promise 的 API 的方法。
这允许您随后await对其进行操作,或者.then像任何其他承诺一样进行调用。
您可以在代码中利用这一点,通过链接返回的承诺,s3.putObject().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
})
Run Code Online (Sandbox Code Playgroud)
也许使用 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);
Run Code Online (Sandbox Code Playgroud)