簡體   English   中英

Promise function 返回未定義

[英]Promise function returns undefined

求助,我只是想學promise function。 我很困惑如何返回 promise function 值。

static getTrailer(movieId) {
    return fetch(`http://api.themoviedb.org/3/movie/${movieId}?api_key=###&append_to_response=videos`)
        .then(response => {
            return response.json();
        })
        .then(responseJson => {
            if (responseJson.videos.results[0]) {
                Promise.resolve(responseJson.videos.results[0].key)
                    .then(result => {
                        console.log(result);
                        return result;
                    });
            } else {
                return Promise.reject(`Trailer is not found`);
            }
        });
}

這是我試圖得到結果的地方

<p>${DataSource.getTrailer(this._movie.id).then(resultKey => {console.log("data is: " + resultKey)})}</p>

但是 resultKey 總是返回未定義的值。 我怎樣才能解決這個問題?

if (responseJson.videos.results[0]) { then you don't return anything ,所以 promise 解析為未定義。

你為什么還要對Promise.resolve做任何事情呢?

去掉多余的 promise, then返回你想要解決的值。

    .then(responseJson => {
        if (responseJson.videos.results[0]) {
            const result = responseJson.videos.results[0];
            console.log(result);
            return result;
        } else {
            return Promise.reject(`Trailer is not found`);
        }
    });

您無需再次使用 promise 來獲取密鑰。


static getTrailer(movieId) {
    return fetch(`http://api.themoviedb.org/3/movie/${movieId}?api_key=###&append_to_response=videos`)
        .then(response => {
            return response.json();
        })
        .then(responseJson => {
            if (responseJson.videos.results[0]) {
                result = responseJson.videos.results[0].key;
                console.log(result);
                return result;
            } else {
                return Promise.reject(`Trailer is not found`);
            }
        });
}

要將數據向下傳遞到 promise 鏈,您需要return (顯式地或從箭頭函數隱式地返回)

就是這樣,又好又簡單;

static getTrailer(movieId) {
    return fetch(`http://api.themoviedb.org/3/movie/${movieId}?api_key=###&append_to_response=videos`)
    .then(response => response.json())
    .then(responseJson => responseJson.videos.results[0].key) // an error thrown for whatever reason, will caught below.
    .catch(error => {
        // an error thrown by any of the three preceding stages will end up here
        throw new Error(`Trailer is not found`); // throwing is less expensive than returning Promise.reject()
    });
}

暫無
暫無

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

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