如何从axios promise对象获取数据?

时间:2019-08-08 05:22:24

标签: javascript axios

我想从axios Promise数据中获取变量,但是它没有分配我的变量。

const axios = require('axios');

let url = 'localhost:3000'
let id = ''
let token = 'my-token'

let api = axios.create({
    baseURL: url,
    withCredentials: false,
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        "Access-Control-Allow-Origin": "*"
    }
})

const getNotices = function (id, token) {
    var arr = []
    let result = api
        .request({
            url: `/notices/${id}/${token}`,
            method: "get",
        })
        .then(res => {
            arr = res.data
            console.log('in', arr)
        })
    console.log('out', arr)
    return arr
}

getNotices(id, token)

我想打印“ arr”,但结果是api的“内部”和“外部”不同。

以下代码的结果是

out []
in [Array(3)]

我不知道为什么与众不同。

我想将此代码用于vuejs模块,但无法导出数据。


编辑-tyskr的代码

const getNotices = function (id, token) {
    return api
        .request({
            url: `/notices/${id}/${token}`,
            method: "get",
        })
        .then(res => {
            return res.data
        })
}

getNotices(id, token).then(function (arr) {
    console.log(arr)
})

但是我还不能像这样

const getNotices = function (id, token) {
    return api
        .request({
            url: `/notices/${id}/${token}`,
            method: "get",
        })
        .then(res => {
            return res.data
        })
}
var result = []
getNotices(id, token).then(function (arr) {
    result = arr
})

我认为它们有不同的范围吗?

3 个答案:

答案 0 :(得分:1)

您需要使用异步等待,如下所示。

const getNotices = async function (id, token) {
var arr = []
let result = await api
    .request({
        url: `/notices/${id}/${token}`,
        method: "get",
    })
    .then(res => {
        arr = res.data
        console.log('in', arr)
    })
    console.log('out', arr) // this line is executing before the response you get from url so we need to use async await
    return arr

答案 1 :(得分:1)

如果您以以下方式重新排列代码:

const getNotices = function (id, token) {
    var arr = []
    return api
        .request({
            url: `/notices/${id}/${token}`,
            method: "get",
        })
        .then(res => {
            arr = res.data
        })
}

getNotices(id, token).then(function(arr){
    console.log(arr); //should solve your issue
})

然后,您应该可以获得一致的arr值。

让我知道这是否无效...

答案 2 :(得分:0)

您必须获取响应的第一个索引

const axios = require('axios');

let url = 'localhost:3000'
let id = ''
let token = 'my-token'

let api = axios.create({
  baseURL: url,
  withCredentials: false,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    "Access-Control-Allow-Origin": "*"
  }
})

const getNotices = function(id, token) {
  var arr = []
  let result = api
    .request({
      url: `/notices/${id}/${token}`,
      method: "get",
    })
    .then(res => {
      arr = res.data[0]
      console.log('in', arr)
    })
  console.log('out', arr)
  return arr
}

getNotices(id, token)