gpt4 book ai didi

javascript - http请求后如何返回值?

转载 作者:行者123 更新时间:2023-12-03 01:18:27 24 4
gpt4 key购买 nike

var content = 'now - not content';

const getHtmlCode = function(){
request(url, function(req, resp, body){
content = body;
});
return content;
};

console.log(getHtmlCode()); // >> now - not content

在控制台中,我可以看到/now - not content/,因为对网站的请求需要 2-3 秒。

糟糕的解决方案:我可以在返回时添加 setTimeout,但这是非常糟糕的方式。

我如何才能在返回内容之前等待?

最佳答案

在您的情况下,在回调中执行 console.log() 操作,即

var content = 'now - not content';

const getHtmlCode = function(){
request(url, function(req, resp, body){
console.log(body);
});
};

getHtmlCode();

如果您更喜欢使用 Promise,您可以尝试下面的代码;

function getHtmlCode(){
return new Promise ((resolve, reject)=>{
request(url, function(req, resp, body){
if(!body) reject({message: "No body"});
resolve(message);
});
});
}

getHtmlCode().then((body)=>{
console.log(body)
}).catch(err=>{
console.log(err);
})

关于javascript - http请求后如何返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51885716/

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