亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

循環多個等待或承諾

循環多個等待或承諾

莫回無 2023-06-09 14:57:53
之后我確實上傳了文件,我將它們的數據保存在 mongo 中,但是如果我處理一個文件,它就可以工作,但是 loop/forEach/map/for 無論如何都不工作文件循環        await Promise.all(files.map(async (file) => {           let url= await uploadFileAndSave(req, file);            await saveFileDB(file,url);        } ))上傳文件功能承諾    return new Promise(async (resolve, reject) => {        let pathDir = req.params.uId + "/";        let typeFolder = getTypeFolder(file.name);        console.log("type", typeFolder);        if (typeFolder) {            pathDir += req.body.app ? req.body.app + "/" : "";            pathDir += req.body.appId ? req.body.appId + "/" : "";            pathDir += typeFolder + "/";            currentPath = path.join(__dirname, "../uploads/", pathDir, Date.now() + "__" + file.name)            console.log("currentPath", currentPath);            file.mv(currentPath).then(async () => {                console.log("sAAaved!!!", file.name);                resolve(currentPath)            })        }    })}保存數據庫功能saveFileDB = async (file, pathUrl) => { return new Promise(async(resolve, reject) => { let name = pathUrl.slice(pathUrl.lastIndexOf('/') + 1, pathUrl.length) let newFile = new fileModel({     name,     url: pathUrl,     dateCreated: Date.now(),     size: file.size / 1024 / 1024,     icon: iconsClasses[file.name.split(".")[1]],     delete: false, }); // console.log("newFile",newFile); try {     let result = await newFile.save();     console.log("save in db", result); } catch (err) {     console.log(err);     res.send(err); }   newFile.save((err, fileSaved) => {     if (err){       console.log("err",err);       reject(err)}       console.log('fileSaved',fileSaved);     resolve(fileSaved)   }); })}
查看完整描述

1 回答

?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

盡量弄清楚你是想要一個承諾,還是要解決的結果

在您的第一個代碼塊中,您正確地打算組裝一個承諾列表,以便您可以將它們與 a 合并Promise.all,然后等待整個結果,與await.


但是,在我看來,您不小心await在內部函數(在.map)內分別對每個 promise 進行了處理,因此輸入的數組Promise.all不再是一個 promise 數組。


而不是這個:


await Promise.all(files.map(

    async (file) => {

       let url= await uploadFileAndSave(req, file);

       await saveFileDB(file,url); 

       // This inner function "async (file) => ..." does not 

       // have a `return` statement, so it returns `undefined`, rather than 

       // the promise you intended to return. This is because you `await`ed 

       // the promise already, rather than `return`ing it to the outer loop.

    } 

))

我建議這樣做:


await Promise.all(files.map(

    async (file) => {

        let url= await uploadFileAndSave(req, file);

        return saveFileDB(file,url); 

        // Now the inner "async (file) =>" function returns

        // a promise (because that is the result type of saveFileDB)

    } 

))

作為文體問題,您可能還想將“let url =”更改為“const url =”。每當您知道您正在創建一個變量,其值在被銷毀之前不會改變時,將其標記為const. 這在調試時(例如,在代碼變長之后)對讀者和您自己都有幫助,而且當您嘗試重新分配它時,Javascript 甚至您的代碼編輯器都會警告您。


查看完整回答
反對 回復 2023-06-09
  • 1 回答
  • 0 關注
  • 118 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號