【问题标题】:Promise object not returning a valuePromise 对象不返回值
【发布时间】:2019-06-30 19:42:44
【问题描述】:

我正在尝试获取asset的值:

const asset = getAssetInformation(11002);

function getAssetInformation(id) {
    return axios({
        method: 'GET',
        url: "/asset-information",
        params: {assetId: id}
    });
}

console.log(asset);

结果是:

[object Promise]

如何从请求中获取返回值?

【问题讨论】:

标签: javascript ajax axios


【解决方案1】:

使用asyncawait是一种实用的方法-

function axios(query) { // fake axios, for demo
  return new Promise (r =>
    setTimeout(r, 1000, { asset: query.params.assetId })
  )
}

function getAssetInformation(id) {
  return axios({
    method: 'GET',
    url: "/asset-information",
    params: {assetId: id}
  })
}

async function main() { // async
  const asset = await getAssetInformation (11022) // await
  console.log(asset)
}

main()
// 1 second later ...
// { asset: 11022 }

【讨论】:

    【解决方案2】:

    Promises 返回另一个 Promise。

    解压和使用promise的方法是通过.then()函数,它会在promise返回后运行。

    const asset = getAssetInformation(11002);
    
    function getAssetInformation(id) {
        return axios({
            method: 'GET',
            url: "/asset-information",
            params: {assetId: id}
        });
    }
    

    这里的资产是一个承诺,你想在它上面使用一个 then 来获取价值。

    而不是..

    const asset = getAssetInformation(11002);
    

    使用

    getAssetInformation(11002)
    .then((response) => {
    //What you returned will be here, use response.data to get your data out.
    
    } )
    .catch((err) => {
    //if there is an error returned, put behavior here. 
    })
    

    【讨论】:

      【解决方案3】:

      您将需要使用 .then 函数。

      const asset = getAssetInformation(11002)
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
      

      【讨论】:

        猜你喜欢
        • 2016-08-31
        • 1970-01-01
        • 1970-01-01
        • 2017-08-01
        • 2016-05-18
        • 2022-01-01
        • 1970-01-01
        • 2018-11-03
        • 2021-04-03
        相关资源
        最近更新 更多