简体   繁体   English

了解Node JS中的Promise?

[英]Understanding promises in node js?

I am learning promises in node js.I have written a piece of code as below. 我正在节点js中学习promises,我写了一段代码如下。

var request = require("request");
var userDetails;

function getData(url) {
    // Setting URL and headers for request
    var options = {
        url: url,
        headers: {
            'User-Agent': 'request'
        }
    };
    // Return new promise 
    return new Promise(function (resolve, reject) {
        // Do async job
        request.get(options, function (err, resp, body) {
            if (err) {
                reject(err);
            } else {
                resolve(body);
            }
        })
    })
}

var errHandler = function (err) {
    console.log(err);
}

function main() {
    var userProfileURL = "https://api.githshub.com/users/narenaryan";
    var dataPromise = getData(userProfileURL);
    // Get user details after that get followers from URL
    var whichPromise = dataPromise.then(JSON.parse)
        .then(function (result) {
            userDetails = result;
            // Do one more async operation here
            console.log("then1")
            var anotherPromise = getData(userDetails.followers_url).then(JSON.parse);
            return anotherPromise;
        })
        .then(function (data) {
            return data
        });
    console.log(whichPromise)

    whichPromise.then(function (result) {
        console.log("result is" + result)

    }).catch(function (error) {
        console.log("Catch" + error)
    });
}


main();

Now this works just fine. 现在,这很好。 I have queries in this regard. 我对此有疑问。

1.How JSON.Parse able to parse data without getting json string in argument. 1. JSON.Parse如何解析数据而不在参数中获取json字符串。

var whichPromise = dataPromise.then(JSON.parse)

2.If i put a wrong url in below line 2.如果我在下面的行中输入错误的URL

var userProfileURL = "https://api.githshub.com/users/narenaryan";

then it's then block will not work because DNS will not be resolved & should get an error which means 那么它的阻止将不起作用,因为无法解析DNS并应获取错误,这意味着

 var anotherPromise = getData(userDetails.followers_url).then(JSON.parse);
            return anotherPromise;

will not return any value and whichPromise will not have any reference. 将不会返回任何值,并且whichPromise将没有任何引用。

but if call below code 但是如果调用下面的代码

whichPromise.then(function (result) {
        console.log("result is" + result)

    }).catch(function (error) {
        console.log("Catch" + error)
    });

here whichPromise is able to call the catch block. 在这里whichPromise可以调用catch块。 can someone explain why ? 有人可以解释为什么吗?

How JSON.Parse able to parse data without getting json string in argument. JSON.Parse如何能够解析数据而不在参数中获取json字符串。

var whichPromise = dataPromise.then(JSON.parse)

.then() expects you to pass it a function. .then()希望您将其传递给函数。 When the promise resolves, it will call that function and pass it the resolved value of the promise. 当承诺解决时,它将调用该函数并将其传递给承诺。

So, you are passing it the JSON.parse function and then it will call that function and pass it the result value of the promise which will be your JSON string. 因此,您将其传递给JSON.parse函数,然后它将调用该函数并向其传递promise的结果值,该结果将是您的JSON字符串。 The return value of executing that function will become the resolved value of the resulting promise in the chain. 执行该函数的返回值将成为链中所得promise的已解析值。 So, in your case the Javascript object that JSON.parse() returns becomes the resolved value of your promise chain. 因此,在您的情况下, JSON.parse()返回的Javascript对象将成为您的Promise链的已解析值。

If I put wrong URL in ... 如果我在...中输入错误的网址...

A wrong URL will obviously not fetch the data you want. 错误的URL显然不会获取您想要的数据。 Depending upon the wrong URL, it will either create a networking error (such as DNS error resolving the host) or return a 404 error (no such path on that host) or the server could return some other type of response. 根据错误的URL,它将创建网络错误(例如解析主机的DNS错误)或返回404错误(该主机上没有此类路径),或者服务器可能返回其他类型的响应。 What exactly gets returned from the request.get() depends upon the options you pass to request.get() and exactly how the URL is wrong. request.get()返回的确切内容取决于传递给request.get()的选项以及URL的错误方式。 In some cases, the promise will get rejected and in that case your .then() handler will not get called. 在某些情况下,promise将被拒绝,在这种情况下,您的.then()处理函数将不会被调用。 In other cases, the promise may still get resolved, but there will be no data or improper JSON passed to JSON.parse() result is some other error. 在其他情况下,promise可能仍然可以解决,但是将没有数据或不正确的JSON传递给JSON.parse()结果是其他错误。

It's important to understand that getting back a 404 response code when you send an invalid path with an http request is NOT considered an http error by many libraries. 重要的是要理解,当您使用http请求发送无效路径时,取回404响应代码不会被许多库视为HTTP错误。 You reached the server, you sent it a request, it processed that request and returned you a response. 您到达了服务器,向它发送了一个请求,它处理了该请求并返回了响应。 Though the response might be a 404 status code, that is not necessarily considered an error. 尽管响应可能是404状态代码,但不一定认为是错误。 So, your own code has to either configure the http library you're using to force a 404 or any 4xx to be an error or you have to explicitly check for that so you handle it properly. 因此,您自己的代码必须配置用于强制404或任何4xx的http库,或者将其显式检查为正确处理。

lets try to understand it step by step. 让我们逐步了解它。

1 1个

=> dataPromise.then(JSON.parse)

This is just equal to as writing 这等于写作

=> dataPromise.then(data => JSON.parse(data))

Because, JSON.parse is a method that takes some data (string) as first input, and returns parsed JS-Object. 因为JSON.parse是一种将一些数据(字符串)作为第一个输入并返回已解析的JS-Object的方法。 But, in a clear picture it's a pure function. 但是,从清晰的角度来看,这是一个纯粹的功能。

What in second line i did to clear your concept i passed anonymous arrow-function that also thats an arg (data) as first arg and returns what JS.parse() method returns. 在第二行中,为了清除您的概念,我通过了匿名箭头功能,该功能也将arg(数据)作为第一个arg,并返回JS.parse()方法返回的内容。 So, we are creating an extra layer or execution context. 因此,我们正在创建一个额外的层或执行上下文。 That extra context is called "point" 这种额外的上下文称为“点”

=> dataPromise.then(data => JSON.parse(data)) with-extra function layer => dataPromise.then(data => JSON.parse(data))带附加功能层

=> dataPromise.then(JSON.parse) passed JSON.parse directly (arg => parsedObj) => dataPromise.then(JSON.parse)直接传递JSON.parse(arg => parsedObj)

This example official software vocabulary is called "point-free programming". 该示例官方软件词汇表称为“无点编程”。

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

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