Javascript 保证不归还任何东西?

Javascript 保证不归还任何东西?,javascript,async-await,Javascript,Async Await,我一直在尝试将我的承诺语法从then/catch转换为async/await,但由于某种原因,它现在无法返回我的承诺。 这是then/catch版本,返回的数据非常好 let lotFiles = [] export function returnData(key) { getContentWithKey(key) .then(content => { if (content.previousHash === '') { lotFiles.push(conte

我一直在尝试将我的承诺语法从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)
  }
}
您可以将内部承诺链替换为
wait

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)
  }
}

您的顶级代码也不应该返回任何内容。。。它没有返回承诺链,而您的底层代码应该返回承诺,因此应该使用
wait
调用。然后(…)
在它上面。那么如何让代码返回
lotFiles
?它可以记录它,但无法返回it@JorahFriendzone您如何验证它是否工作?代码出现在您的问题中,而不是注释中