I need to wait for a api response to return before the subsequent result to be executed. So I tried with promise calls in js. But still it doesn't wait for the api response. My attempt is as below.
getAgentList(data); //here data object receiving data
console.log("executed before the api response");
var getAgentList = function (dataFromMsg) {
const myPromise = new Promise(function (resolve, reject) {
let accountNum = window.localStorage.account;
fetch("/web/main?account=" + accountNum, {
method: "GET",
})
.then(function (res) {
return res.json();
})
.then(function (data) {
let friendArrList = data.data.friend[0].list;
for (let i = 0; i < friendArrList.length; i++) {
if (friendArrList[i].id == dataFromMsg.id) {
dataFromMsg.avatar = friendArrList[i].avatar;
dataFromMsg.username = friendArrList[i].username;
break;
}
}
dataFromMsgG = JSON.parse(JSON.stringify(dataFromMsg)); //dataFromMsgG is global object
resolve("fine");
})
.catch((error) => {
console.error("Error:", error);
reject("error");
});
});
myPromise
.then(function whenOk(response) {
console.log("response", response);
return response;
})
.catch(function notOk(err) {
console.error(err);
});
};
}
But it will print "executed before the api response" line without waiting for api response. So where I was get wrong and how could be wait until the api response get success?
I suggest to use await
and async
with promise. Since the await is only valid in async function then I have to put your code in a async
function which I named it as main .
<script>
main();
async function main() {
await getAgentList();
console.log("executed before the api response");
function getAgentList() {
const myPromise = new Promise(function (resolve, reject) {
///...
///... Your code
///...
});
myPromise
.then(function whenOk(response) {
console.log("response", response);
return response;
})
.catch(function notOk(err) {
console.error(err);
});
return myPromise;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.