代码之家  ›  专栏  ›  技术社区  ›  AmazingDayToday

承诺对象不返回值

  •  -3
  • AmazingDayToday  · 技术社区  · 7 年前

    我想知道 asset :

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

    结果是:

    [object Promise]
    

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

    3 回复  |  直到 7 年前
        1
  •  0
  •   Mulan    7 年前

    使用 async await 是一种实用的方法-

    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
  •  0
  •   Aditya Bhave    7 年前

    你需要使用。然后功能。

    const asset = getAssetInformation(11002)
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      });
    
        3
  •  -1
  •   Sam    7 年前

    承诺会返回另一个承诺。

    解包和使用Promise的方法是通过.then()函数,该函数将在Promise返回后运行。

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

    这里的资产是一个承诺,你要用一个然后在它上面得到价值。

    而不是。。

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