CIOC
CIOC

Reputation: 1427

JavaScript promise and Node.js

I have a simple Node.js server in which I'm trying to use a Node.js package called image-similarity, according to its doc it is used like this:

let  imageSimilarity  = require ('image-similarity') ; 
imageSimilarity('./image/1.jpg', './image/2.jpg').then ( res =>  { 
    console.log(res) ; // The  similarity is 0.8162515507509954 
} ) ;

It works fine like that but I'm trying to use it inside an HTTP Node.js server, like this:

var http = require('http');
var imageSimilarity = require('image-similarity');

http.createServer(function handler(req, res) {
    res.writeHead(200, {'Content-Type' : 'text/plain'});

    var result = "";

    imageSimilarity('./images/1.png', './images/2.png').then(res => {
        result = res;
    });

    res.end(result);
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

I just need to add the result to the response, but I found that I cannot access the res variable from inside the then function, and I cannot simply assign the result to a variable like in the previous example since that block is executed asynchronously it will simply be empty when I try to use it outside.

Upvotes: 1

Views: 53

Answers (1)

andy mccullough
andy mccullough

Reputation: 9541

You are running into problems with it being async, you need to call res.end(result) from within your then()

var http = require('http');
var imageSimilarity = require('image-similarity');

http.createServer(function handler(req, res) {
    res.writeHead(200, {'Content-Type' : 'text/plain'});

    imageSimilarity('./images/1.png', './images/2.png').then(result => {
        res.end(result);
    });


}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

also I note I renamed the then's argument to result to avoid naming clashes with the outer res

Upvotes: 2

Related Questions