Javascript 承诺 return

Javascript promise return

我正在尝试创建一个函数,该函数 return 是使用承诺的 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);

我不想做控制台日志,而是想 return google.com 的正文以便我可以使用它。这只是一个范围问题,但我不确定如何解决它。谢谢,

您可以 return 承诺,然后当您调用 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)
    });