简体   繁体   English

使用 Javascript 承诺时出现未知错误

[英]Unknown Error while using Javascript promises

I am new to Javascript and trying to understand how promises work.我是 Javascript 的新手,并试图了解承诺的工作原理。 I have written the below code to call a REST API and resolve the response.我编写了以下代码来调用 REST API 并解决响应。

const buyFlightTicket = () => {
    return new Promise( (resolve, reject) => {
        setTimeout( () => {
            let commentResponse = fetch('https://jsonplaceholder.typicode.com/comments/1'); 
            commentResponse
                .then(response => {
                    if (response.status == 200) {
                        resolve(response.json());
                    } else {
                        reject("Failed to fetch comment: " + response.statusText);
                    }
                })
                .reject("Failed to fetch comment");
        }, 3000);
    })
}

buyFlightTicket()
.then( (responseData) => console.log(responseData))
.catch( (error) => console.log(error));

I am able to log the response data but I am getting Error: Unknown error just before the response is being logged to the console.我能够记录响应数据,但在将响应记录到控制台之前出现错误:未知错误。

What is causing this error?是什么导致了这个错误?

Also, how do i rewrite this code using callbacks without using Promise?另外,如何在不使用 Promise 的情况下使用回调重写此代码?

You should use the catch , not .reject您应该使用catch ,而不是.reject

            commentResponse
                .then(response => {
                    if (response.status == 200) {
                        resolve(response.json());
                    } else {
                        reject("Failed to fetch comment: " + response.statusText);
                    }
                })
                .catch(() => "Failed to fetch comment");

you can use fetch, which also return a promise您可以使用 fetch,它也返回 promise

const buyFlightTicket = () => {
    let commentResponse = fetch('https://jsonplaceholder.typicode.com/comments/1'); 
    return commentResponse
        .then(response => {
            if (response.status == 200) {
                return (response.json());
            } else {
                return new Error("Failed to fetch comment: " + response.statusText);
            }
        })
}

buyFlightTicket()
.then( (responseData) => console.log(responseData))
.catch( (error) => console.log(error));

If the browser doesn't support the Promise , you can add the polyfill or you can use the xhr如果浏览器不支持Promise ,你可以添加polyfill或者你可以使用 xhr

    var buyFlightTicket = function(cb, errorCb) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://jsonplaceholder.typicode.com/comments/', true);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4){
                if (xhr.status === 200){
                  cb(xhr.responseText)
                } else {
                  errorCb(xhr.statusText);
                }
            }
        };


        xhr.send(null);
        xhr.onerror = function (e) {
            console.error(xhr.statusText);
        };
        console.log('end')
    }
    buyFlightTicket(successCb, errorCb)
    function successCb(res) {
        console.log(res);
    }
    function errorCb(err) { console.log(err) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM