簡體   English   中英

NodeJS使用Promise的正確方法

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM