剛剛自己再啄磨了一下子,果然是自己太嫩了,
是因為由python再學js
python 比較直觀... 剛入手js, 回調函數,異步與同步都未用得純熟就要處理該問題,煩了很幾天
果然真的要再由零學起就會明白得更多
另外想說明,不可使用forEach 去建立promise
以下是我参考了 https://zellwk.com/blog/async-await-in-loops/ 所得出的解:
<button @click="myDownload_btn">myDownload_btn</button>
myDownload_btn() {
let tmpDict = {} //空字典,用於保存{ "原本檔案名" : "保存檔案名" }
const urlList = [ //要下載的url array
'https://ns-strategy.cdn.bcebos.com/ns-strategy/upload/fc_big_pic/part-00270-3760.jpg',
'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1947872534,1823906830&fm=26&gp=0.jpg',
'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1034074796,4011346817&fm=26&gp=0.jpg'
]
const myDownload = (url_index) => { //參考教學的sleep
return new Promise(resolve => {
let urlAddress = urlList[url_index]
uni.downloadFile({
url:urlAddress,
success:(res)=>{
console.log('DL sucess,tmpPath = ',res.tempFilePath)
uni.saveFile({
tempFilePath:res.tempFilePath,
success: (savedRes) => {
tmpDict[url_index] = savedRes.savedFilePath //更新tmpDict的內容
resolve() //釋放promise鎖<< 我自己定義,python也有類似東西
}
})
}
})
})
}
const myJob = (url_index) => { //參考教學的getNumFruit
return myDownload(url_index).then(v => urlList[url_index])
}
const control = async _ => {
console.log('Start')
for (let i = 0;i<3;i++){
let DL_Job = await myJob(i)
}
console.log(tmpDict)
console.log('End')
}
control() //程序入口
},
samshum22 (作者)
感謝回覆
2021-05-18 11:50