我试图绕过承诺,但到目前为止,我似乎无法得到简单的例子。这是一个从服务器请求JSON的代码:
module.exports = function (app, options) {
var promise = require('bluebird');
var request = require('request-json');
var module = {
url: options.url,
httpClient: promise.promisifyAll(request.createClient(options.url))
};
module.getSample = function() {
return this.httpClient.getAsync('sample/')
.then(function(error, response, body) {
console.log(body);
})
.catch(function(e) {
console.log('error');
console.log(e);
});
};
return module;
};
但是当我这样称呼时:
var backendClient = require('./utils/backendClient.js')(app, {
url: 'http://localhost:8080/'
});
backendClient.getSample()
在运行时我收到一条错误,说“' [SyntaxError:Unexpected token o]'。没有承诺的版本工作正常。我错过了什么?
答案 0 :(得分:1)
module.getSample = function() {
return this.httpClient.getAsync('sample/')
.then(function(error, response, body) {
// not sure what Promise library you are using, but in the Promise/A+ spec, the function in then only receives a single argument, the resolved value of the Promise
console.log(body);
// this returns equivalent to Promise.resolve(undefined);
// you really want to return something meaningful here
})
.catch(function(e) {
console.log('error');
console.log(e);
// this also returns equivalent to Promise.resolve(undefined);
// to propagate the "error" condition, you want to either throw e, or return Promise.reject(something here);
});
};
这将始终返回一个完整的承诺,其中 undefined 为值,绝不会被拒绝。上面评论的其他错误