简体   繁体   English

我如何在node.js中将npm请求模块与bluebird一起使用

[英]How can I use npm request module with bluebird in node.js

webCheck.js webCheck.js

var request = require("request");
var Promise = require("bluebird");



module.exports = {
    check : function(address){
        var length;
        request(address).on('response',function(response){
        response.on('data',function(data){
            length = data.length;
            console.log("in : ",length); //  
        })
    });
    console.log("out : ",length);
    return length;
}
}


main.js main.js

var webCheck = require('./webCheck.js');

    module.exports = {
    run : function(){
        console.log("result : ",webCheck.check("http://localhost:3000/status"));
        ...


Terminal 终奌站

out :  undefined
result :  undefined
in : 821

I want to check the length of the website. 我想检查网站的长度。 However, the function that checks the website is not synchronous. 但是,检查网站的功能不是同步的。

I want to return length after the request has been completed. 我想在请求完成后返回长度。

How can I do? 我能怎么做? I want to use bluebird module. 我想使用bluebird模块。

To be able to use the request module with bluebird promises, the documentation suggests to install request-promise . 为了能够将request模块与bluebird Promise一起使用, 文档建议安装request-promise So after installing request , also npm install request-promise . 因此,在安装request ,还要npm install request-promise

Then you have to make sure the check function returns this promise, so the caller can wait for it's result: 然后,您必须确保check功能返回此承诺,以便调用方可以等待其结果:

var request = require("request-promise");

module.exports = {
    check : function(address) {
        return request(address)
            .on('response', function(response) {
                return response;
            });
    }
}

Finally, the call in the main.js needs to wait for the promise to resolve, before the result can be used: 最后,main.js中的调用需要等待promise解析,然后才能使用结果:

var webCheck = require('./webCheck.js');

module.exports = {
    run : function() {
        webCheck.check("http://localhost:3000/status").then(function(response) {
            console.log(response);
        });
    }
    ...
}

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

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