最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

NodeJS使用Promise的正确方法

IT培训 admin 2浏览 0评论

NodeJS使用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发送请求,解析链接,将它们添加到数组并在控制台中写入。在控制台中写完后,我调用了resolve()函数,因为Promise已经完成。

第二个功能是:

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

PrintMe()打印到控制台的所有链接后,GetLinks()函数应该简单地打印出来。

我按此顺序打电话给他们:

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

NodeJS使用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发送请求,解析链接,将它们添加到数组并在控制台中写入。在控制台中写完后,我调用了resolve()函数,因为Promise已经完成。

第二个功能是:

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

PrintMe()打印到控制台的所有链接后,GetLinks()函数应该简单地打印出来。

我按此顺序打电话给他们:

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

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论