我正在尝试使用promise来创建一个返回api调用主体的函数。我的代码是
function checkApi(link) {
var promise = new Promise(function(resolve, reject) {
//query api
});
promise.then(function(value) {
console.log(value); //want to return this, this would be the body
}, function(reason) {
console.log(reason); //this is an error code from the request
});
}
var response = checkApi('http://google.com');
console.log(response);
我想返回google.com的主体,而不是做控制台日志,以便我可以使用它。这只是一个范围问题,但我不知道如何解决它。谢谢,
答案 0 :(得分:2)
您可以退回承诺,然后在致电checkApi时,您可以附加另一个.then()
。
function checkApi(link) {
var promise = new Promise(function(resolve, reject) {
//query api
});
return promise.then(function(value) {
console.log(value); //Here you can preprocess the value if you want,
//Otherwise just remove this .then() and just
return value; //use a catch()
}, function(reason) {
console.log(reason); //this is an error code from the request
});
}
//presuming this is not the global scope.
var self = this;
checkApi('http://google.com')
.then(function (value){
// Anything you want to do with this value in this scope you have
// to do it from within this function.
self.someFunction(value);
console.log(value)
});