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
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.
To be able to use the request
module with bluebird promises, the documentation suggests to install request-promise
. So after installing request
, also 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:
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:
var webCheck = require('./webCheck.js');
module.exports = {
run : function() {
webCheck.check("http://localhost:3000/status").then(function(response) {
console.log(response);
});
}
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.