作者pthread (QQ)
看板Ajax
标题[问题] call api promise改成同步执行
时间Thu Sep 28 14:53:43 2023
以下是程式码片断
变数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="
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://webptt.com/cn.aspx?n=bbs/Ajax/M.1695884029.A.6B7.html
1F:推 LPH66: Promise 本身就已经不是同步的了, 你要做的是在 then() 09/29 07:50
2F:→ LPH66: 里面的函数里 (那里才有收到回应) 去做後续操作 09/29 07:50
3F:→ LPH66: 像是你这里的 forEach 那样, 写在那个函数里 09/29 07:53
4F:推 VdustR: 感觉你需要的是 async await 10/06 22:07
5F:→ y3k: await 01/02 16:10
6F:推 qoo02255: var 已经不推荐使用很久了,容易有bug,换成let 比较好 05/19 21:40