async 、await 、Promise 學習記錄 、在vue 的for循環中實現 同步調用接口


async 、await 、Promise 學習記錄

知識點


//執行async 函數,返回的都是Promise 對象
async function test1() { 
    return 1;
 }
 async function test2() { 
    return Promise.resolve(2);
 }
 const result1 = test1();
 const result2 = test2();
 console.log('result1',result1);
 console.log('result2',result2);

 //Promise.then 成功的情況 對應await
async function test3(){
    const p3 = Promise.resolve(3);
    p3.then(data3 =>{
        console.log('data3',data3);
    })
    const data3 = await p3;
    console.log('data3',data3);
}
test3();


async function test4(){
    const data4 = await 4; //等價於 await Promise.resolve(4)
    console.log('data4',data4);
}
test4();


async function test5(){
    const data5 = await test1();
    console.log('data5',data5);
}
test5();
 //Promise.catch 異常的情況 對用 try...catch

 async function test6(){
    const p6 = Promise.reject(6);
    try{
        const data6 = await p6;
        console.log('data6',data6);
    }catch (e){
        console.error('捕獲到的異常console.error',e);
    }
}
test6();




未完待續……

在vue 的for循環中實現 同步調用接口

async forFunc(){
  for (let i = 0; i < 5; i++) {
           await  this.addRoom(i);
        }

},
//serviceApi.addRoom  是封裝的請求
 async addRoom(value) {
      await serviceApi
        .addRoom({lease_id: value})
        .then((res) => {
          if (res.success) {
          console.log(value);
          } else {
            let str = "";
            res.msg.forEach((element) => {
              str = str + element + "<br/>";
            });
            this.$message({
              type: "error",
              dangerouslyUseHTMLString: true,
              message: str,
            });
          }
        });
    },


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM