Reputation: 433
I've been trying to convert my promise syntax from then/catch to async/await and for some reason it's now unable to return my promise. This is the then/catch version which returns the data perfectly fine
let lotFiles = []
export function returnData(key) {
getContentWithKey(key)
.then(content => {
if (content.previousHash === '') {
lotFiles.push(content)
return lotFiles
}
lotFiles.push(content)
returnData(content.previousHash)
})
.catch(err => {
console.log(err);
})
}
This is the async/await version which doesn't return anything at all
let lotFiles = []
async function returnData(key) {
try {
let content = await getContentWithKey(key)
if (content.previousHash === '') {
lotFiles.push(content)
return lotFiles
} else {
lotFiles.push(content)
returnData(content.previousHash)
}
} catch (e) {
console.log(e);
}
}
I have another function that calls returnData -
async function returnContent(data) {
let something = await getContent(data)
console.log(something)
}
returnContent()
Upvotes: 0
Views: 94
Reputation: 5425
async/await
requires a promise chain.
The returnData()
function is recursive so you can place the inner most result in an array and push the other results in the chain.
async function returnData(key) {
try {
const content = await getContentWithKey(key)
if (content.previousHash === '') {
// termination of recursion
// resolve with an array containing the content
return Promise.resolve([content])
}
else {
return returnData(content.previousHash).then(function(result) {
// append the result and pass the array back up the chain
return [content].concat(result)
})
}
}
catch(error) {
return Promise.reject(error)
}
}
You can replace the inner promise chain with await
.
async function returnData(key) {
try {
const content = await getContentWithKey(key)
if (content.previousHash === '') {
// termination of recursion
// resolve with an array containing the content
return Promise.resolve([content])
}
else {
try {
let result = await returnData(content.previousHash)
// append the result and pass the new array back up the chain
return [content].concat(result)
}
catch(error) {
return Promise.reject(error)
}
}
}
catch(error) {
return Promise.reject(error)
}
}
Upvotes: 1