本文介绍了从 Meteor.method 中的回调返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些我对 Meteor 不理解的问题.我有这个方法,它接受一个查询,将它发送到亚马逊,然后在该函数的回调中我尝试返回结果.

I am running into something I don't understand with Meteor. I have this method, which takes a query, sends it to amazon, and then in the callback of that function I try to return the results.

Meteor.methods({
    'search': function(query) {
        var bookInfo;
        if (Meteor.isServer) {
            amazon.execute('ItemSearch', {
                'SearchIndex': 'Books',
                'Keywords': query,
                'ResponseGroup': 'ItemAttributes'
            }, function(results) {
                bookInfo = results;
                console.log(bookInfo);
                return bookInfo;
            });
        }
    }
});

但是当我将以下内容放入浏览器 (chrome) 的控制台时:

But when I put the following into the console in my browser (chrome):

Meteor.call('search', 'harry potter', function(error, response) {
    console.log('response:', response);
});

我明白了:

undefined
response: undefined          VM13464:3

我想我明白第一个 undefined 来自没有在客户端返回任何内容的方法,但回调似乎根本不起作用.

I think I understand that the first undefined comes from the method not returning anything on the client, but the callback doesn't seem to work at all.

amazon.execute(...) 肯定会返回一些东西,因为返回上方的 console.log 确实记录了我正在寻找的信息.

The amazon.execute(...) is definitely returning something, as the console.log right above the return does log the info I'm looking for.

知道出了什么问题以及如何解决吗?

Any ideas what's going wrong and how I can fix it?

推荐答案

你需要使用未来来实现你的目标.

You need to use Future to achieve your goal.

Meteor 0.6 以后如何使用future?

How to use future since Meteor 0.6?

Meteor.startup(function () {
 Future = Npm.require('fibers/future');

 // use Future here
}

你用 Future 重写的方法:

Your method rewritten with Future:

Meteor.methods({
 'search': function(query) {

    var future = new Future();

    amazon.execute('ItemSearch', {
            'SearchIndex': 'Books',
            'Keywords': query,
            'ResponseGroup': 'ItemAttributes'
    }, function(results) {
       console.log(results);

       future["return"](results)

    });

    return future.wait();
 }
});

现在它应该可以工作了.

Now it should work.

Meteor.call('search', 'harry potter', function(error, response) {
   if(error){
    console.log('ERROR :', error);
   }else{
    console.log('response:', response);
   }

});

如果您想了解有关 Future 库的更多信息,我建议您观看 截屏视频

If you want to learn more about Future library I recommend watching screencast

26/12/2017 更新

Update on 26/12/2017

我只是想更新这个答案,因为您可以使用 promise 实现同样的目的,因此摆脱纤维"依赖:)

I just wanted to update this answer as you can achieve the same thing using promise and so, get rid of the "fibers" depedencies :)

一个例子值一千字

import scrap from 'scrap';

Meteor.methods({
    'hof.add'(el) {
        check(el, {
            _link: String
        });

        const promise = getHofInfo(el._link)
            .then((inserter) => {
                inserter.owner = Meteor.userId();
                Hof.insert(inserter);
                return true;
            })
            .catch((e) => {
                throw new Meteor.Error('500', e.message);
            });
        return promise.await();
    }
});


function getHofInfo(_link) {
    return new Promise((resolve, reject) => {
        scrap(_link, function (err, $) {
            if (err) {
                reject(err);
            } else {
                const attakers = $('#report-attackers').find('li').text();
                const defender = $('#report-defenders').find('li').text();
                const _name = attakers + ' vs ' + defender;
                const _date = new Date();
                resolve({ _name, _date, _link });
            }
        });
    });
}

这篇关于从 Meteor.method 中的回调返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-28 19:38