Javascript promise return [duplicate]

2019-08-29 05:43发布

问题:

This question already has an answer here:

  • How do I return the response from an asynchronous call? 35 answers

I'm trying to make a function that returns the body of an api call using a promise. My code is

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);

Instead of doing console log, I want to return the body of google.com so that I can use it. This is just a scope problem, but I'm not sure how to fix it. Thanks,

回答1:

You can return the promise and then when you call the checkApi you can attach another .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)
    });