我需要使用此軟體包下載影像- 但有時,其中一個影像已損壞。在這里,兩個示例影像之一已損壞,我正在添加一個 Math.random() 來模擬這種情況。我現在正在嘗試在.catch()發生后重新啟動程式- 問題是程式無限運行。我該如何解決這個問題?
我的代碼是:
let imgArrays = ["https://upload.wikimedia.org/wikipedia/commons/d/dc/Gigi1.jpg", "https://mms.businesswire.com/media/20211119005773/fr/929256/5/Aries_Linden_mechanical_completion_11-19-2021.jpg"]
const runingImage = () => {
const url = imgArrays[Math.floor(imgArrays.length * Math.random())];
const path = 'img/image.jpg'
options = {
url: url,
dest: path
}
download.image(options)
.then(({
filename
}) => {
console.log('Saved to', filename)
}).catch(
(err) => {
console.log("running again");
return runingImage();
})
}
runingImage();
當我運行它時,它現在只給我:
running again
running again
...
Until I stops the console.
uj5u.com熱心網友回復:
不幸的是,您陷入了所有程式員在某個時候都陷入(并且仍在下降)的陷阱:丟失檔案/檔案夾
當您仍處于開發階段時,請始終在 catch 陳述句中列印錯誤。這就是你會得到并最終自己解決問題的結果:
console.log(err)
ENOENT:沒有那個檔案或目錄,打開'img/image.jpg'
還有你正在做的這個小錯誤。您正在創建一個void型別函式并嘗試return其值始終為undefined
解決方案:
img在您放置此檔案的目錄中創建一個檔案夾。- 洗掉
returncatch 塊內的單詞,只留下runingImage();
uj5u.com熱心網友回復:
洗掉回傳陳述句。它應該是這樣的:
let imgArrays = ["https://upload.wikimedia.org/wikipedia/commons/d/dc/Gigi1.jpg", "https://mms.businesswire.com/media/20211119005773/fr/929256/5/Aries_Linden_mechanical_completion_11-19-2021.jpg"]
const runingImage = () => {
const url = imgArrays[Math.floor(imgArrays.length * Math.random())]
const path = 'img/image.jpg'
options = {
url: url,
dest: path
}
download.image(options)
.then(({
filename
}) => {
console.log('Saved to', filename)
}).catch(
(err) => {
console.log("running again")
})
}
runingImage()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/398161.html
標籤:javascript 节点.js
