簡體   English   中英

為什么 Axios(帶有 async/await)會返回一個完整的 promise?

[英]Why does Axios (with async/await) return a full promise?

我有async / await問題。 這是我的代碼:

 import axios from 'axios' export default async function getRequestedData (requestAddress, params) { return await axios.get(requestAddress, {params: params}) }

但是它返回一個完整的承諾而不是結果,所以數據大量嵌套在一個承諾中:

在此處輸入圖片說明

就像 Ha Ja 說的,我認為你仍然需要解決這個承諾。 如果你只是返回 await 你會得到一個承諾。

const fs = require ('fs')

function getText () {

    return new Promise( (resolve, reject) => {

        fs.readFile('./foo.txt', 'utf8', (err, data) => {
            if (err) {
                reject(err)
            }
                resolve(data)
            })
        })
}

async function output () {
    try {
        let result = await getText()
        console.log("inside try: ", result)
        return result
    }
    catch (err){
        console.log(err)
    }
}

console.log("outside: ", output())
output().then( result => console.log("after then: ", result))

// outside:  Promise { <pending> }
// inside try:  foo text
// inside try:  foo text
// after then:  foo text

您必須返回數據:

const response = await axios.get(requestAddress, {params: params})
return response.data;

一個班輪:

return (await axios.get(url)).data;

在 React 組件中,您可以使用以下技巧:

function InitProduct() {
    // Get your product from database
    var productId = 'abc';
    axios.get('/api/products/' + productId).then(response => {
        $('.' + productId).text(response.data.ProductTitle);
    });

    return (<div className={productId}></div>)
}

export class TestNow extends Component {
    render() {
        return (
            <div>
                {InitProduct()}
            </div>
        )
    }
}

異步函數將始終將它返回​​的內容包裝在承諾中,因此您應該使用 then() 方法鏈接調用者,從而解決該承諾,例如: getRequestedData (requestAddress, params).then ( (data) => { ...do某物... });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM