[英]Vercel/Netlify serverless functions lifecycle. Can code run after response?
我有一個無服務器 function 從 github api 獲取數據並將其保存到文件系統以緩存它。
我當前的代碼如下所示
export async function cachedFetch(url: string, options: RequestInit, cacheKey: string){
let file = Path.join(tmpPath,cacheKey+".cache");
function obtainAndCache(){
return fetch(url, options).then(async r=>{
let text = await r.text();
writeFile(file,text).catch(console.error); // note: don't await the file write
return text;
})
}
if (existsSync(file)){
let stat = await lstat(file);
let timeOfLastFetch = stat.mtime.valueOf();
let time = Date.now();
let timeSinceLastFetch = time - timeOfLastFetch;
if (timeSinceLastFetch >= MINUTE){
obtainAndCache().catch(console.error); // note: don't await the request
}
let text = String(await readFile(file));
return text;
} else {
return obtainAndCache();
}
}
我的程序流程應該是這樣的:
檢查緩存(緩存不包含資源)->開始獲取->獲取完成->開始將資源寫入文件->使用獲取的資源解析->完成寫入文件
檢查緩存(緩存包含資源)->開始獲取->使用緩存資源解析->使用緩存資源響應客戶端->獲取完成->開始將資源寫入文件->完成寫入文件
正如您在這兩種情況下看到的那樣,在服務器響應客戶端之后我仍然有代碼在運行。
所以我的問題是:
我正在尋找 vercel and.netlify 的具體答案。
目前我正在使用.netlify,但我願意切換到vercel。
我不是 100% 確定,因為我不熟悉 what.netlify 期望,但如果你與向你發送請求的工具交互的唯一方式是通過對該請求的響應,那么這是一個很好的用例步驟功能。
一旦您的 labda 返回 - 向 .netlify 發送響應 - 您想要召喚一個新的 lambda 來處理文件寫入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.