Javascript promise return [duplicate]

眉间皱痕 提交于 2019-12-12 03:37:42

问题


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


来源:https://stackoverflow.com/questions/31909460/javascript-promise-return

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!