最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - axios.post().then() not passing resolved data to callback function - Stack Overflow

programmeradmin1浏览0评论

When I use axios.post(...).then(data=>callback(data)) the data is not defined when I access it in the callback, however, a console log right before the data is accessed shows all the data.

I've tried all the binations of async await that's possible. I feel like this is a way simpler problem than I'm making it.

// passed in as successCallback
const handleCreationCompleted = data => {
    console.log(data)

    // Error below ReturnedDataObject not defined
    var object = data.ReturnedDataObject

}

const createObject = async (variables, successCallback, errorCallback) => {
    ...
    await axios.post(url, form_data, {
        headers: {
    ...
        },
    }).then(res => {
        successCallback(res)
    })
    .catch((err) => {
        errorCallback(err)
    })

I should be able to access the data, which is a json object (it's fetched from a graphql api) within the successcallback

When I use axios.post(...).then(data=>callback(data)) the data is not defined when I access it in the callback, however, a console log right before the data is accessed shows all the data.

I've tried all the binations of async await that's possible. I feel like this is a way simpler problem than I'm making it.

// passed in as successCallback
const handleCreationCompleted = data => {
    console.log(data)

    // Error below ReturnedDataObject not defined
    var object = data.ReturnedDataObject

}

const createObject = async (variables, successCallback, errorCallback) => {
    ...
    await axios.post(url, form_data, {
        headers: {
    ...
        },
    }).then(res => {
        successCallback(res)
    })
    .catch((err) => {
        errorCallback(err)
    })

I should be able to access the data, which is a json object (it's fetched from a graphql api) within the successcallback

Share Improve this question asked Oct 16, 2019 at 23:52 KyleKyle 3038 silver badges22 bronze badges 2
  • 1 Can you show us an example of what you get from the console.log? – Matt Aft Commented Oct 17, 2019 at 0:21
  • @MattAft This suggestion lead to me realising I had to access a chain of data.data.data, the way the promises were chained and how graphql returns the data. Thanks. – Kyle Commented Oct 17, 2019 at 0:35
Add a ment  | 

1 Answer 1

Reset to default 5

You're using await with then(). You should switch to one. If you use await, assign the result to a variable. You should also be passing back the data of the response and not the response itself.

const response = await axios.post(...)
callback(response.data)

If you want to use then, then it's:

axios.post(...)
.then(respone => callback(response.data))
发布评论

评论列表(0)

  1. 暂无评论