简体   繁体   English

NodeJS使用Promise的正确方法

[英]NodeJS correct way to use Promise

I have two simple functions: 我有两个简单的功能:

  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();

         }

})})}

The function GetLinks() sends a request to URL, parse links, add them to the array and write in the console. 函数GetLinks()向URL发送请求,解析链接,将其添加到数组中并在控制台中写入。 After writing in the console I call resolve() function as Promise is fulfilled. 在控制台中写入后,当Promise完成时,我将调用resolve()函数。

The second function is: 第二个功能是:

function PrintMe() {
    const initializePromise = GetLinks();
    initializePromise.then(function()
    {
       console.log("it's done");
    })
}

The function PrintMe() should simply print it's done after GetLinks() prints all links to the console. GetLinks()所有链接打印到控制台后,函数PrintMe()只需将其打印出来即可。

I'm calling them in this order: 我按以下顺序打电话给他们:

GetLinks();
PrintMe();

The problem is that sometimes "it's done" is printed in the middle of links and sometimes on the end. 问题在于,有时“完成”显示在链接的中间,有时显示在末尾。 Why it does not print "it's done" always on the end? 为什么它不总是在最后打印“完成”? My goal is to wait for GetLinks to be fully finished and then simply call another function. 我的目标是等待GetLinks完全完成,然后简单地调用另一个函数。

From what you've posted I can only give you this much of an answers: 从您发布的内容来看,我只能给您这么多答案:

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 is making a request. getLinks正在发出请求。 printMe is calling getLinks inside of it again and that's why two promises overlap. printMe再次在其内部调用getLinks ,这就是两个getLinks重叠的原因。 Change printMe so that it only prints something. 更改printMe ,使其仅打印某些内容。

And then call them like this. 然后这样称呼他们。

getLinks().then(printMe)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM