0
var request = require("request-promise"),
    parseXml = require("xml2js").parseString,
    q = require("q");

exports.getEntities = function(entity, callback) {
    var uri = "http://lookup.dbpedia.org/api/search/PrefixSearch?QueryClass=&MaxHits=5&QueryString=" + entity;

    var options = {
        uri : uri,
        method : "GET",
        transform : function (data) {
            var deferred = q.defer();
            parseXml(data, function(err, result) {
                deferred.resolve = result.ArrayOfResult.Result;
            });

            return deferred.promise;
        }
    };

    return request(options);
};

parseXml uses a call back, but I need to return a value from the transform function. I've tried the above, but because the caller of transform is not expecting a promise it's not doing what I wanted. How can I return the result of parseXml to transform?

baynezy
  • 6,493
  • 10
  • 48
  • 73
  • 1
    If the function is asynchronous, then the caller needs to expect an asynchronous interaction with it. You cannot adapt a function which runs asynchronously internally to appear synchronously externally. – deceze Jun 03 '15 at 07:22
  • `the caller of transform is not expecting a promise` - Normally the caller should adopt to the callee's functionality. Also, it should have been `deferred.resolve(result.ArrayOfResult.Result);` – thefourtheye Jun 03 '15 at 07:26
  • Promises don't return values. They return an object that accepts a callback via it's `then(callback)` method (this object is known as a Promise). Weather or not you use a promise doesn't matter. You still need to pass a callback - you can't return a value. – slebetman Jun 03 '15 at 08:07

0 Answers0