I am trying to convert my async-await function to the old school Promises way.
The main challenge is that I need to loop through a function and use the response to fetch more.
Here is my function:
async function getHierarchyForId(id) {
try {
let result = '';
let member = await fetchMemberById(id)
let tmp = member.parentMemberId
console.log(member)
for(let i = member.level; i > 1; i--){
let parent = await fetchMemberById(tmp)
console.log(parent)
if(i == 2){
result = `${parent.name}`
}else{
result = `${parent.name} -> `
}
tmp = parent.parentMemberId
}
console.log(result)
return result
}catch(e){
console.log(e)
}
}
This is correctly working, and I try to translate that to a promise function.
Here is what I got, but some wrong code is written.
async function getHierarchyForId(id) {
fetchMemberById(id)
.then(member => {
let result = '';
let tmp = member.parentMemberId
for (let i = member.level; i > 1; i--) {
let parent = fetchMemberById(tmp)
.then(r => {
console.log(r)
if (i == 2) {
result = `${r.name}`
} else {
result = `${r.name} -> `
}
tmp = parent.parentMemberId
})
.catch(err => console.log(err))
}
console.log(result)
return result
})
.catch(e => console.log(e))
}
Thank you for your time !
CodePudding user response:
Yes, any async/await
code can be translated to then/catch
code.
For your case you'll need to make an "asynchronous loop": create a function that gets the first promise, and then as a then
callback action, (later) calls that new function again, so chaining promises until the final result is known, at which point all those promises resolve.
function getHierarchyForId(id) {
return fetchMemberById(id).then(member => {
console.log(member);
return (function loop(id, i, arr) {
if (i <= 1) return arr.join(" -> "); // loop done
return fetchMemberById(id).then(parent => {
console.log(parent);
return loop(parent.parentMemberId, i-1, arr.concat(parent.name));
});
})(member.parentMemberId, member.level, []); // Start of the loop
}).catch(e => {
console.log(e)
});
}