gpt4 book ai didi

javascript - Meteor:如何调用带有2个参数的函数并等待结果

转载 作者:行者123 更新时间:2023-11-28 14:48:28 27 4
gpt4 key购买 nike

我一直在阅读有关 promises 的内容, wait/asyncfibers在过去的几天里,但我仍然无法理解它。我很难找到一个简单的例子来展示我如何制作这样的东西:

Meteor.methods({
theMethod: function(){
var numberOne = 4;
var numberTwo = 5;
var result = calculateNumber(numberOne, numberTwo);
console.log('This is the result: ', result);
}
});

calculateNumber = function(numberOne, numberTwo){
var result = numberOne + number Two
//but lets assume an ultra complex calculation that takes a while
return result;
}

如何让 console.log 等待结果返回而不使用回调,而是使用 wait/wrapAsync 语法?

提前致谢! :)

编辑:

这是我尝试过的代码:

Meteor.methods({
theMethod: async function(){
const no1 = 4, no2 = 5;
//calculateNumber should return a promise, if it doesnt, Promise.resolve makes the returned value a promise
const calculateNumberPromise = Promise.resolve(calculateNumber(no1, no2));
const res = await calculateNumberPromise;
console.log('Number calculated', res);
//the number can be returned directly to the client:
return res
}
});

calculateNumber = function(no1, no2){
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
sleep(5000).then(() => {
return no1 + no2;
});
}

有没有办法让calculateNumber之后的所有事情都等待?如果这是不可能的,我必须在哪里/如何嵌套 console.log 才能使其等待?

最佳答案

仅使用Promise(即没有async/await),您可以执行以下操作:

Meteor.methods({
theMethod: () => {
const no1 = 4, no2 = 5;
//calculateNumber should return a promise, if it doesnt, Promise.resolve makes the returned value a promise (unless calculateNumber is a sync function ie takes a callback)
const calculateNumberPromise = Promise.resolve(calculateNumber(no1, no2));
//If you want to log the output regardless:
calculateNumberPromise
.then(res => console.log('Number calculated', res))
.catch(err => console.log('Error calcualting number', err))
//The promise is resolved before the data is sent over the wire.
return calculateNumberPromise;
}
});

然后可以在客户端调用此方法并使用 Promise。理想情况下,您应该使用 validated methods现在。与经过验证的方法结合使用,您可以使用 callPromise mixin 。示例已链接。更多 validated method examples可以在 meteor 指南中找到。

调整前面的代码片段以使用async很简单:

Meteor.methods({
theMethod: async function() {
const no1 = 4, no2 = 5;
//calculateNumber should return a promise, if it doesnt, Promise.resolve makes the returned value a promise
const calculateNumberPromise = Promise.resolve(calculateNumber(no1, no2));
const res = await calculateNumberPromise;
console.log('Number calculated', res);
//the number can be returned directly to the client:
return res;
}
});

请注意函数定义中添加的async。还可以找到一篇优秀文章 here - 查看 Rob Fallows 的其他文章。

wrapAsync 足够简单,但我建议坚持使用 Promiseasync/await。如果您确实想使用它,可以在 Meteor chef's site 上找到一些旧的(但很好的)示例。 .

如果有任何不清楚的地方,请要求澄清。

关于javascript - Meteor:如何调用带有2个参数的函数并等待结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45493370/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com