我有两个简单的功能:
function GetLinks() {
return new Promise(function(resolve) {
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
// Print out the response body
let rawcookies = response.headers['set-cookie'];
const $ = cheerio.load(body)
$('.entry-title a[href]').each((index, elem) => {
let newItem = (index, $(elem).attr('href'))
listOfArticleLinks.push(newItem);
});
listOfArticleLinks.forEach(function (item, index, array) {
console.log(item);
});
resolve();
}
})})}
函数GetLinks()
向URL发送请求,解析链接,将其添加到数组中并在控制台中写入。在控制台中写入后,随着Promise的完成,我调用resolve()
函数。
第二个功能是:
function PrintMe() {
const initializePromise = GetLinks();
initializePromise.then(function()
{
console.log("it's done");
})
}
PrintMe()
函数只需打印即可,它是在GetLinks()
打印到控制台的所有链接之后完成的。
我按此顺序打电话给他们
GetLinks();
PrintMe();
问题在于,有时“完成”显示在链接的中间,有时显示在末尾。为什么它不总是在最后打印“完成”?我的目标是等待GetLinks完全完成,然后简单地调用另一个函数。
答案 0 :(得分:1)
根据您发布的内容,我只能给您这么多答案:
function GetLinks() {
// const options = ... // fill in your option here
return promisifiedRequest(options).then(({response, body}) => {
let rawcookies = response.headers["set-cookie"]; // unused variable?
const $ = cheerio.load(body);
$(".entry-title a[href]").each((index, el) => {
console.log($(elem).attr("href"));
});
});
}
function printMe() {
console.log("It's done!");
}
// this is your old plain request, but wrapped in a promise
function promisifiedRequest(options) {
return new Promise(function(resolve, reject) {
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
// what is passed here is going to be
// available in .then call
resolve({ response, body });
} else {
reject("Oopps, can't request");
}
});
});
}
GetLinks()
.then(printMe)
.catch(error => console.error(error)); // handle errors
答案 1 :(得分:-1)
getLinks
正在发出请求。 printMe
在其内部再次调用getLinks
,这就是两个承诺重叠的原因。
更改printMe
,使其仅打印出一些内容。
然后这样称呼他们。
getLinks().then(printMe)