繁体   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