[英]Promise not returning anything?
我一直在尝试将我的promise语法从then / catch转换为async / await,由于某种原因,它现在无法返回我的诺言。 这是then / catch版本,可以完美返回数据
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);
})
}
这是异步/等待版本,根本不返回任何内容
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);
}
}
我还有另一个函数调用returnData-
async function returnContent(data) {
let something = await getContent(data)
console.log(something)
}
returnContent()
async/await
需要一个承诺链。
returnData()
函数是递归的,因此您可以将最里面的结果放置在数组中,并将其他结果推入链中。
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)
}
}
您可以使用await
替换内部的Promise链。
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.