[問題] call api promise改成同步執行

看板Ajax作者 (QQ)時間7月前 (2023/09/28 14:53), 編輯推噓2(202)
留言4則, 2人參與, 6月前最新討論串1/1
以下是程式碼片斷 變數sss要怎麼取得call API傳回來的值 在promise外的sss印出來還是空的,好像沒有同步 請教要如何改才會是同步的,謝謝 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>標題</title> <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script> <script src="" rel="nofollow">https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> $(function(){ console.log('開始'); var sss = ""; var pp = get(""); Promise.all([pp]).then(function(responseArray){ console.log(responseArray); responseArray.forEach(function(response,index){ var seed = response.info.seed; console.log(seed); sss = seed; console.log(sss); }); }); console.log(sss); }); function get(url) { return new Promise(function(success,fail){ axios.get('https://randomuser.me/api/') .then(function (response) { // handle success console.log(response); var status = response.status; console.log(status); if(status=="200"){ return success(response.data); }else{ return fail(); } }) .catch(function (error) { // handle error console.log(error); fail(); }) .finally(function () { // always executed }); }); } </script> </head> <body> </body> </html> -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 223.137.226.13 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1695884029.A.6B7.html

09/29 07:50, 7月前 , 1F
Promise 本身就已經不是同步的了, 你要做的是在 then()
09/29 07:50, 1F

09/29 07:50, 7月前 , 2F
裡面的函數裡 (那裡才有收到回應) 去做後續操作
09/29 07:50, 2F

09/29 07:53, 7月前 , 3F
像是你這裡的 forEach 那樣, 寫在那個函數裡
09/29 07:53, 3F

10/06 22:07, 6月前 , 4F
感覺你需要的是 async await
10/06 22:07, 4F
文章代碼(AID): #1b5IBzQt (Ajax)
文章代碼(AID): #1b5IBzQt (Ajax)