我正在制作一個服務,它讀取一個目錄并遍歷電影檔案以獲取它們的名稱和路徑,然后嘗試從電影 API (TMDB) 中查找有關這些檔案的資訊。如果回傳多部電影,則進行另一個 API 呼叫(使用 Axios)以獲取有關每部電影的更具體資訊,然后確定它是否可能是正確的電影。
我的代碼作業了一段時間,但最終停止了,從未真正進入“完成分析”部分。這讓我相信我沒有正確地履行我的所有承諾。我以前使用 async/await 結構進行過這個作業,但我想用 then 等將它轉換為基于 Promise 的結構。
下面提供的是我的代碼的清理版本:
class movieSrcAnalyzer {
async analyze() {
console.log("Starting Analyzer... \n");
fs.promises
.readdir(baseDirectory)
.then((names) => {
const fileCount = names.length;
let currentFileNum = 1;
for (const name of names) {
this.getTMDBid(name).then((data) => {
// This prints around 500 / 700 movies that are in the directory
console.log(`${currentFileNum} / ${fileCount}: `, data);
currentFileNum ;
});
//await this.createMovie(id, path);
}
})
.then(() => "Done with Analysis.")
.catch((error) => console.error(error));
}
async getTMDBid(name) {
const originalName = name;
let cleanName = name;
const partRegex = /part\s([0-9]*)/g;
const partInfo = cleanName.match(partRegex);
cleanName = cleanName.replace(partRegex, "");
cleanName = cleanName.replace(/\.[^/.] $/, "");
cleanName = cleanName.replace("_", " ");
cleanName = cleanName.toLowerCase();
return new Promise((resolve, reject) => {
axios
.get(`http://${IP_ADDRESS}:${PORT}/api/tmdb/search-name/${cleanName}`)
.then((response) => {
const movies = response.data.results;
// If at least one result was found
if (movies && movies[0] !== undefined) {
// If there is only one result, it's likely correct
if (!(movies.length > 1)) {
return { id: movies[0].id, path: originalName };
} else {
// More than one result was found, we must narrow it down.
for (const key in movies) {
const result = movies[key];
return new Promise((resolve, reject) => {
axios
.get(
`http://${IP_ADDRESS}:${PORT}/api/tmdb/search-id/${result.id}`
)
.then((response) => {
const movie = response.data;
getVideoDurationInSeconds(
`${baseDirectory}/${originalName}`
).then((duration) => {
const durationInMinutes = duration / 60;
if (
durationInMinutes > movie.runtime - 1 &&
durationInMinutes < movie.runtime 1
) {
resolve({
id: result.id,
path: originalName,
});
}
});
})
.catch((error) => console.error(error));
if (
result.title.includes(cleanName) ||
result.original_title.includes(cleanName)
) {
// Get more data here.
}
});
}
}
}
return { id: null, path: originalName };
})
.then((movieData) => {
resolve(movieData);
})
.catch((error) => console.error(error));
}).then((data) => {
return data;
});
}
}
我查看了幾個不同的類似問題,但他們的解決方案都不適合我。大多數直接回傳 Axios 回應然后處理資料,但我的需要根據嵌套的 Axios 請求以不同的方式處理資料。我仍然不太擅長圍繞嵌套 Promise 到底發生了什么,所以如果你回答這個問題,我也會很感激你的解決方案如何作業的“為什么”。
uj5u.com熱心網友回復:
關于語法的一些想法:
- 這是尷尬和難以閱讀
async/await的語法與混合.then()。只選擇一種風格。 - 回傳承諾的東西不需要(也不應該)被包裹
new Promise() - 對于
await回圈中生成的承諾,收集它們并await Promise.all()
一些設計理念:
使用單個物件來跟蹤每部電影。看起來所有相關的道具都是:
{ name: '', // the name on disk cleanName: '', // the name filtered thru your regex's runtime: 0, // runtime in seconds, calculated from local data imdbMatch: {}, // object from the api that matches imdbDetail: {} // more data from the api if needed for the match }盡早從磁盤在一個地方構建所有電影資訊。
分解名稱清理邏輯
綜上所述,我建議以下...
class movieSrcAnalyzer {
async analyze() {
console.log("Starting Analyzer... \n");
// for each disk movie, find the best matching imdb movie
const diskMovies = await this.diskMovies(baseDirectory);
const promises = diskMovies.map(movie => {
return this.getIMDBMatch(movie); // will add prop(s) to movie from the best matching imdb data
})
const matchedMovies = await Promise.all(promises);
console.log( "Done with Analysis.")
return matchedMovies
}
// create movie objects from data on disk
async diskMovies() {
const names = await fs.promises.readdir(baseDirectory); // presumes baseDirectory is in containing scope
const promises = names.map(async (name) => {
const cleanName = this.cleanName(name)
const seconds = await getVideoDurationInSeconds(`${baseDirectory}/${name}`);
const runtime = seconds / 60.0; // runtime in minutes
return { name, cleanName, runtime }
});
return Promise.all(promises)
}
cleanName(name) {
let cleanName = name;
const partRegex = /part\s([0-9]*)/g;
const partInfo = cleanName.match(partRegex);
cleanName = cleanName.replace(partRegex, "");
cleanName = cleanName.replace(/\.[^/.] $/, "");
cleanName = cleanName.replace("_", " ");
cleanName = cleanName.toLowerCase();
return cleanName
}
// return a copy of movie with props added that represent the best match found in the api
// movie is { name, cleanName, runtime }
// add 'imdbMatch'
// optionally add 'imdbDetail' if the match required more detail
async getIMDBMatch(movie) {
movie = Object.assign({}, movie)
const response = await axios.get(`http://${IP_ADDRESS}:${PORT}/api/tmdb/search-name/${movie.cleanName}`)
const results = response.data.results;
if (results.length < 2) {
movie.imdbMatch = results.length === 1 ? results[0] : null;
return movie
}
// for more than two results, get detail on them sequentially, compare run length and other factors
for (const result of results) {
const response = await axios.get(`http://${IP_ADDRESS}:${PORT}/api/tmdb/search-id/${result.id}`)
const detail = response.data;
// imdb movie is a match if runtime matches
if (Math.abs(movie.runtime - detail.runtime) < 1) {
movie.imdbMatch = result;
movie.imdbDetail = detail;
return movie
}
// other checks here, like result.title vs movie.cleanName or movie.name
// etc
}
// if we get here, we didn't find a match in the imdb results.
movie.imdbMatch = null;
return movie
}
}
uj5u.com熱心網友回復:
我懷疑問題是這個then塊沒有回傳任何東西
.then((names) => {
const fileCount = names.length;
let currentFileNum = 1;
for (const name of names) {
this.getTMDBid(name).then((data) => {
// This prints around 500 / 700 movies that are in the directory
console.log(`${currentFileNum} / ${fileCount}: `, data);
currentFileNum ;
});
//await this.createMovie(id, path);
}
})
我認為您需要從所有this.getTMDbid呼叫中收集承諾,將它們作為此塊(Promise.all)中的一個承諾回傳,然后做您的"Done with Analysis."事情。目前,我認為then在這條線上沒有什么可做的.then(() => "Done with Analysis.")
這里有一些東西可以用來替換then上面的塊:
.then((names) => Promise.all(names.map(name => this.getTMDBid(name))))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390758.html
標籤:javascript 节点.js 表达 承诺 公理
