【问题标题】:Promise not returning anything?保证不退货?
【发布时间】:2019-01-14 01:41:49
【问题描述】:

我一直在尝试将我的 Promise 语法从 then/catch 转换为 async/await,但由于某种原因,它现在无法返回我的 Promise。 这是 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);
  })
}

这是 async/await 版本,根本不返回任何内容

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

【问题讨论】:

  • 你的顶级代码也不应该返回任何东西......它没有返回 Promise 链
  • 同时,您的底部代码应该返回一个 Promise,因此应该使用 await.then(...) 调用它。
  • 那么如何让代码返回lotFiles?可以登录,但无法返回
  • @JorahFriendzone 你如何验证它没有工作?
  • 代码在您的问题中,不在 cmets 中

标签: javascript async-await


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2018-07-22
    • 2013-01-05
    • 2014-09-03
    • 1970-01-01
    • 2022-11-18
    • 2018-01-01
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    相关资源
    最近更新 更多