如何在客户端使用 Meteor.wrapAsync? [英] How to use Meteor.wrapAsync on the client?

查看:44
本文介绍了如何在客户端使用 Meteor.wrapAsync?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Meteor 客户端代码中,我尝试使用只有异步调用的第三方 API.如何在客户端上使用 Meteor.wrapAsync 以同步方式调用此 API?文档似乎表明这是可能的:http://docs.meteor.com/#/full/meteor_wrapasync

In my Meteor client code, I'm trying to use a third party API that only has asynchronous calls. How can I use Meteor.wrapAsync on the client to make calls to this API in a synchronous style? The docs seem to indicate that this is possible: http://docs.meteor.com/#/full/meteor_wrapasync

以下是我想以同步方式调用的一些示例代码:

Here is some sample code I would like to call in a synchronous style:

var func1 = function(callback) {
  Meteor.setTimeout(function() {
    console.log('func1 executing');
    callback(null, {success: true});
  }, 2000);
};

var func2 = function(callback) {
  Meteor.setTimeout(function() {
    console.log('func2 executing');
    callback(null, {success: true});
  }, 1000);
};

var wrapped1 = Meteor.wrapAsync(func1);
var wrapped2 = Meteor.wrapAsync(func2);

Template.test.rendered = function() {
    wrapped1();
    console.log('After wrapped1()');
    wrapped2();
    console.log('After wrapped2()');
};

目前,这会产生以下输出:

Currently, this produces this output:

After wrapped1()
After wrapped2()
func2 executing
func1 executing

我希望它产生:

func1 executing    
After wrapped1()
func2 executing
After wrapped2()

我已将此代码放入 MeteorPad 中:http://meteorpad.com/pad/fLn9DXHf7XAACd9gq/排行榜

I've put this code into a MeteorPad here: http://meteorpad.com/pad/fLn9DXHf7XAACd9gq/Leaderboard

推荐答案

Meteor.wrapAsync 为了同构代码在客户端上工作.这样您就可以编写可以在客户端和服务器上共享的代码,而不会导致 Meteor 崩溃或抱怨.

Meteor.wrapAsync works on the client for the sake of isomorphic code. This is so you can make code that you can share on the client and server without Meteor crashing or complaining.

客户端上不可能有同步代码.至少不使用并非在所有浏览器上都可用的 ES6 功能.

It is not possible to have synchronous code on the client. At least without using ES6 features which are not available on all browsers.

如 saeimeunt Meteor.wrapAsync 的评论中所述,将需要在客户端进行回调.

As in the comment by saeimeunt Meteor.wrapAsync will require a callback on the client.

这篇关于如何在客户端使用 Meteor.wrapAsync?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆