[英]NodeJS correct way to use Promise
我有两个简单的功能:
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");
})
}
在GetLinks()
所有链接打印到控制台后,函数PrintMe()
只需将其打印出来即可。
我按以下顺序打电话给他们:
GetLinks();
PrintMe();
问题在于,有时“完成”显示在链接的中间,有时显示在末尾。 为什么它不总是在最后打印“完成”? 我的目标是等待GetLinks完全完成,然后简单地调用另一个函数。
从您发布的内容来看,我只能给您这么多答案:
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
getLinks
正在发出请求。 printMe
再次在其内部调用getLinks
,这就是两个getLinks
重叠的原因。 更改printMe
,使其仅打印某些内容。
然后这样称呼他们。
getLinks().then(printMe)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.