以下是程式碼片斷
變數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>