Javascript 带请求承诺的异步/等待返回未定义
我有两个档案;下面是当前的代码片段 server.js:Javascript 带请求承诺的异步/等待返回未定义,javascript,node.js,asynchronous,async-await,cheerio,Javascript,Node.js,Asynchronous,Async Await,Cheerio,我有两个档案;下面是当前的代码片段 server.js: const scrape = require("./scrape"); async function start() { const response = await scrape.start(); console.log(response); } start(); 和scrape.js: const cheerio = require("cheerio"); const request = require("req
const scrape = require("./scrape");
async function start() {
const response = await scrape.start();
console.log(response);
}
start();
和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
};
因此,当我启动server.js时,我会将未定义的返回到console.log(response),当我真的想返回我一直推到的数组时,你能看到我哪里出错了吗?你需要
从async
函数中返回一些东西(a中的返回然后不会从主函数返回)。要么是承诺,要么是你等待的东西
另外,确保声明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);
});
};
由于您使用的是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);
}
};
我相信你的go
函数没有返回任何值
您正在调用请求(选项)。然后(…)
,但是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);
});
};
“go”不应该返回承诺吗?@McMurphy如果我没弄错的话,将其声明为异步函数会自动返回承诺?。each()
使用“回调”。你需要用承诺来包装它,并解决它的结果。否则,代码直接跳到返回空数组。当然,您需要返回请求
结果,但是如果您不尊重回调,那么您仍然会遇到问题。go
是一个错误。不要这样做。为什么你将go
定义为一个async
函数,但却不使用wait
?。每个()都有一个回调,不是吗?@NeilLunn是。每个都使用一个同步回调(所以在这里可以使用)。@NeilLunn(当然,map
应该优先于每个
+推送
)