Javascript 如何從fetch返回Promise取到[[PromiseValue]]值

12 月 28, 2018 | | 0 條留言

如下將fetch寫成函數,返回值時會發現,控制台顯示我的數據Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]],這樣的方式要如何取得資料來應用呢?。

將提取api fetch寫成函式調用

function apiGetAll (api) {
    return fetch(api, {
        headers: { content-type: application/json }
    })
        .then(response => response.json().then(json => ({ json, response })))
        .then(({ json, response }) => {
            if (!response.ok) {
                return Promise.reject(json);
            }

            return json;
        })
        .then(response => response, error => error);
}

我在這裡調用它,但是當我嘗試記錄變量\’api\’

componentDidMount () {
    console.log(Component did mount)
    const api = apiGetAll() 
}

這是我在fetch調用後記錄的響應,Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]它顯示了我的所有數據,但不知道如何取得使用它。

如何讀取fetch函數api數據來應用?

可使用下列兩種方式調用數據

then內的函數返回值

    apiGetAll(apiurl).then(res => this.setState({ data: res.data }));

Promise.resolve調用

    const a = Promise.resolve(apiGetAll(apiurl));
    // Promise {[[PromiseStatus]]: resolved, [[PromiseValue]]: xx}

    a.then(function(result) {
        console.log(result);
    });