javascript 带有请求承诺的异步/等待返回未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47341603/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:18:46  来源:igfitidea点击:

Async/Await with Request-Promise returns Undefined

javascriptnode.jsasynchronousasync-awaitcheerio

提问by razki

I have two files; server.js and scrape.js, below are the code snippets as they currently stand.

我有两个文件;server.js 和 scrape.js,下面是它们目前的代码片段。

server.js:

服务器.js:

const scrape = require("./scrape");

async function start() {
    const response = await scrape.start();
    console.log(response);
}

start();

and scrape.js:

和scrape.js:

const cheerio = require("cheerio");
const request = require("request-promise");

go = async () => {

const options = {
  uri: "http://www.somewebsite.com/something",
  transform: function(body) {
    return cheerio.load(body);
  }
};

request(options)
  .then($ => {
    let scrapeTitleArray = [];
    $(".some-class-in-html").each(function(i, obj) {
      const data = $(this)
        .text()
        .trim();
      scrapeTitleArray.push(data);
    });
    return scrapeTitleArray;
  })
  .catch(err => {
    console.log(err);
  });
};

module.exports = {
  start: go
};

So when I spin up server.js, I return undefined to the console.log(response), when I actually want to return the array i've been pushing to, can you see where I'm going wrong?

因此,当我启动 server.js 时,我将 undefined 返回到 console.log(response),当我实际上想要返回我一直推送到的数组时,你能看出我哪里出错了吗?

回答by Alexander O'Mara

You need to returnsomething from your asyncfunction (a return inside a then does not return from the main function). Either a promise or something you await-ed.

你需要return从你的async函数中得到一些东西(然后在 a 中返回不会从主函数返回)。要么是承诺,要么是你await写过的东西。

Also, make sure to declare your govariable to avoid leaking it into the global space.

另外,请确保声明您的go变量以避免将其泄漏到全局空间中。

const go = async () => {

  const options = {
    uri: "http://www.somewebsite.com/something",
    transform: function(body) {
      return cheerio.load(body);
    }
  };

  return request(options)
    .then($ => {
      let scrapeTitleArray = [];
      $(".some-class-in-html").each(function(i, obj) {
        const data = $(this)
          .text()
          .trim();
        scrapeTitleArray.push(data);
      });
      return scrapeTitleArray;
    })
    .catch(err => {
      console.log(err);
    });
};

Since you are using an asyncfunction, you might want to take advantage of the awaitsyntax also.

由于您使用的是async函数,因此您可能还想利用await语法。

const go = async () => {

  const options = {
    uri: "http://www.somewebsite.com/something",
    transform: function(body) {
      return cheerio.load(body);
    }
  };

  try {
    const $ = await request(options);
    $(".some-class-in-html").each(function(i, obj) {
      const data = $(this)
        .text()
        .trim();
      scrapeTitleArray.push(data);
    });
    return scrapeTitleArray;
  }
  catch (err) {
    console.log(err);
  }
};

回答by Gershom

I believe your gofunction isn't returning any value.

我相信你的go函数没有返回任何值。

You're calling request(options).then(...), but what follows from that promise is never returned by go. I recommend you add a returnstatement:

您正在调用request(options).then(...),但是从该承诺中得出的内容永远不会被 返回go。我建议你添加一个return声明:

go = async () => {

  const options = {
    uri: "http://www.somewebsite.com/something",
    transform: function(body) {
      return cheerio.load(body);
    }
  };

  // The only difference is that it says "return" here:
  return request(options)
    .then($ => {
      let scrapeTitleArray = [];
      $(".some-class-in-html").each(function(i, obj) {
        const data = $(this)
          .text()
          .trim();
        scrapeTitleArray.push(data);
      });
      return scrapeTitleArray;
    })
    .catch(err => {
      console.log(err);
    });
};