【问题标题】:How to wait for async data before send response using promises and arrow functions?如何在使用承诺和箭头函数发送响应之前等待异步数据?
【发布时间】:2019-01-18 09:42:02
【问题描述】:

我是 ES6 新手,箭头函数和 Promise,我不知道如何使用它们,更糟糕的是一起使用。

我使用 REST 生成器 (https://github.com/diegohaz/rest) 启动了一个项目,它工作正常,但我需要修改部分身份验证。

我需要在身份验证期间从第三方服务器返回数据。我创建了使用 axios 正确返回数据的函数,但是我无法将此信息与其他信息(来自此项目)一起返回,之前已发送响应。

下面是生成的代码,几乎不可触碰,我只加了extraData: user.getExtraData(user)

// function in auth controller file
export const login = ({ user }, res, next) => {
  sign(user.id)
    .then((token) => ({
      token, user: user.view(true), extraData: user.getExtraData(user)
    }))
    .then(success(res, 201))
    .catch(next)
}

// function in user model file
view (full) {
    let view = {}
    let fields = ['id', 'name', 'picture']
    if (full) {
      fields = [...fields, 'email', 'createdAt']
    }
    fields.forEach((field) => { 
      view[field] = this[field] 
    })     
    return view
}

这是我添加到用户模型中的功能

getExtraData (userView) {
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
    axios.post( userView.host, querystring.stringify( {
      data1:userView.data1,
      data2:userView.data2
    }))
      .then((response) => {
        return response.data
      })
      .catch((error) => {
        console.log('Error', error)
        return null        
      })
}

如何让响应等到 extraData 使用给定代码从 getExtraData 函数返回?谢谢

【问题讨论】:

  • getExtraData 不返回任何东西——它唯一可以返回的有用的东西是一个承诺......所以extraData: 将是一个承诺,而不是一个价值
  • @JaromandaX 是的......但是如何将 response.data 分配给 extraData?
  • 异步!

标签: javascript node.js asynchronous promise arrow-functions


【解决方案1】:

您可以使用 async/await。在这种情况下,您需要为getExtraData 发送await。因此logingetExtraData内部的匿名函数都需要声明为异步函数:

// function in auth controller file
export const login = ({ user }, res, next) => {
    sign(user.id)
    .then(async (token) => ({
        token, 
        user: user.view(true), 
        // Wait for getExtraData to finish using await
        extraData: await user.getExtraData(user)
    }))
    .then(success(res, 201))
    .catch(next)
}

async getExtraData (userView) {
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

    try {
        const response = await axios.post( userView.host, querystring.stringify( {
            data1:userView.data1,
            data2:userView.data2
        }))

        return response.data
    }
    catch (err){
        return null
    }
}

【讨论】:

  • @Daniel 让我知道这是否适合您。否则,告诉我出了什么问题
  • 嗨,我在等待 user.getExtraData(user) 时遇到错误。 SyntaxError: auth/controller.js: await 是保留字
  • 嘿....你帮了我很多,现在它正在工作。我需要解决一件小事。我不得不将 async 放入 .then(async (token) => ({ 而不是 export const login = async ({ 谢谢
  • 天啊!你是对的丹尼尔。事实上,我从来没有注意到对getExtraData 的调用是在另一个函数中。感谢您指出并编辑我的答案。我不得不即时帮助你,因为我无法检查代码。如果您现在认为答案是正确的,请将其标记为已接受(绿色复选标记)。这可以帮助其他人解决同样的问题。提前致谢!
猜你喜欢
  • 2018-02-03
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多