[英]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.