所以,我不知道如何正确处理这个问题。
我想做的是:
// client side
Meteor.call("getData", url, function(images) {
console.log(images); // get array of image src
});
// server side
Meteor.methods({
"getData": (url) => {
var images = [];
// here is where I am lost
// scrape the images
scrape.request(url, function(err, $) {
if (!err) {
$('img').each(function(img) {
let src = img.attribs.src;
images.push(src);
}
// so at this point, I can console log an array on the server, but I need to bring it back to the client
}
} // now, how do I push all these and then signal to return the array?
return images; // returns undefined, not waiting for all the data
// I'm not sure how to wait for the array to be updated.
}});
想法?
所以,回顾一下,我想获取从传递给 Meteor 方法的网站中抓取的所有图像源的数组。
最佳答案
有一个很好的tutorial上Meteor.wrapAsync这说明了这一点。另外this previous answer提供更多详细信息并解释错误处理。
所有操作都发生在服务器上。对于您的情况:
Meteor.methods({
getData(url) => {
const syncScrape = Meteor.wrapAsync(scrape.request);
try {
const $ = syncScrape(url,{});
let images = [];
$('img').each(img => {
images.push(img.attribs.src);
});
return images;
}
catch(error) {
throw new Meteor.error(error);
}
}
});
您的客户端调用还需要包含回调中的错误:
Meteor.call("getData", url, (error, images) => {
if (!error) console.log(images); // get array of image src
});
关于javascript - meteor JS : Handling an async function inside another async function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43859591/