栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Meteor:在服务器上正确使用Meteor.wrapAsync

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Meteor:在服务器上正确使用Meteor.wrapAsync

Meteor.wrapAsync
您可以看到需要向其传递一个函数和一个可选的上下文,而在两次尝试中,您都传递了调用异步版本的结果
Stripe.customers.create

Meteor.methods({  stripeCreateUser: function(options) {    // get a sync version of our API async func    var stripeCustomersCreateSync=Meteor.wrapAsync(Stripe.customers.create,Stripe.customers);    // call the sync version of our API func with the parameters from the method call    var result=stripeCustomersCreateSync({      description: 'Woot! A new customer!',      card: options.ccToken,      plan: options.pricingPlan    });    // do whatever you want with the result    console.log(result);  }});

Meteor.wrapAsync
将异步函数转换为方便的同步外观函数,该函数允许编写顺序查找的代码。(底层仍然在异步Node.js事件循环中执行所有操作)。

我们需要将函数上下文与函数上下文一起传递给

Meteor.wrapAsync
我们的API函数(
Stripe.customers.create
),即
this
在API函数的主体内部(在本例中为)
Stripe.customers

编辑:

如何找回错误?

传统的节点样式API函数通常将回调作为最后一个参数,当所需的任务完成时,它将最终被调用。此回调采用2个参数:error和data,根据调用结果,其中任一个将为null。

我们如何使用返回的同步包装函数访问错误对象

Meteor.wrapAsync

我们必须依靠使用try / catch块,因为如果发生错误,它将由sync函数抛出,而不是作为异步函数回调的第一个参数传递。

try{  var result=syncFunction(params);  console.log("result :",result);}catch(error){  console.log("error",error);}// is the equivalent of :asyncFunc(params,function(error,result){  if(error){    console.log("error",error);    return;  }  console.log("result :",result);});

为什么不需要通过Stripe?

Javascript没有“命名空间”概念,因此API开发人员使用了一种通用技巧,即定义充当API名称空间的全局对象,在此对象上定义的属性是API的“子模块”。这意味着它

Stripe.customers
是Stripe
API的子模块,用于公开与客户相关的功能,因此这些功能
this
上下文
Stripe.customers
不是
Stripe

您可以通过将以下模拟代码复制粘贴到浏览器控制台中来自己进行测试:

Stripe={  customers:{    create:function(){      console.log(this==Stripe.customers);    }  }};

然后像这样在浏览器控制台中调用存根函数:

> Stripe.customers.create();true


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/464750.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号