gpt4 book ai didi

JavaScript promise 返回

转载 作者:行者123 更新时间:2023-12-02 15:50:05 26 4
gpt4 key购买 nike

我正在尝试创建一个使用 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 的正文,以便我可以使用它。这只是一个范围问题,但我不知道如何解决它。谢谢,

最佳答案

您可以返回 Promise,然后当您调用 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)
});

关于JavaScript promise 返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31909460/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com