I can't get my API callback to execute before the rest of code.
(我无法在其余代码之前执行API回调。)
I always get the set element console logs, then the next step, then the callbacks.(我总是得到set元素控制台日志,然后是下一步,然后是回调。)
Earlier versions of this pattern did not have a Promise in the actual callback.(此模式的早期版本在实际的回调中没有Promise。)
I don't think it was needed but wanted to make sure that wasn't the issue.(我认为这不是必需的,但想确保这不是问题。)
const xhrReqBase = function(req) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
resolve(xhr.responseText);
} else if(xhr.readyState === 4 && xhr.status !== 200) {
reject();
}
};
xhr.open(req.method, req.url, true);
xhr.send(JSON.stringify(req.requestBody));
});
};
const xhrReq = async function(req) {
let resp = await xhrReqBase(req);
await req.callback(JSON.parse(resp));
};
const userReq = {
method: "GET",
url: "https://jsonplaceholder.typicode.com/users",
callback: function(resp) {
return new Promise(function(resolve, reject) {
console.log("...callback");
console.log(resp);
resolve();
});
}
};
const getUsers = async function(valFromSetEle) {
console.log("...a set element value:"+valFromSetEle);
await xhrReq(userReq);
};
let aSet = new Set();
aSet.add(1);
aSet.add(2);
aSet.add(3);
//Either way below has the same result
//await aSet.forEach(getUsers);
// OR
//await aSet.forEach(async function(valFromSetEle) {
// await getUsers(valFromSetEle);
//});
console.log("...next step");
ask by mikeatv translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…