0
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,但这是非常糟糕的方式。

我怎样才能在返回内容之前等待?

4

1 回答 1

1

在您的情况下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);
})
于 2018-08-16T22:00:21.657 回答