带有等待/承诺的流星呼叫似乎没有同步



我一直在尝试以同步方式调用meteor.call。我试着效仿流星论坛上给出的例子,但似乎不起作用。

const callWithPromise = (method, myParameters) => {
return new Promise((resolve, reject) => {
Meteor.call(method, myParameters, (err, res) => {
if (err) reject('Something went wrong');
resolve(res);
});
});
}

下面的函数没有等待以上结果,doStuff()在调用后立即返回。

async function doStuff() {
const myValue1 = await callWithPromise('myMethod1', someParameters);
const myValue2 = await callWithPromise('myMethod2', myValue1);
}

如有上述内容,我们将不胜感激。

是的,await并没有完全达到您的预期(或想要(。然后它需要包含在要使用的async函数中:(它仍在处理promise,您需要注意这一点

然而,Meteor确实提供了一个Promise实现,它允许人们在不需要进入异步函数的情况下等待。

import { Promise } from 'meteor/promise'

在你的代码中,你可以这样做:

const result = Promise.await(Metor.call('server-method',params))

result然后包含Meteor方法返回的内容,因此它的行为类似于常规函数调用。

正如Bergi已经指出的,即使是异步函数也会立即返回——顾名思义!——即使你被允许在里面等待。因此,您也需要等待异步函数。下面是一个简化的例子:

const wait = () => { return new Promise((resolve, reject) => setTimeout(resolve, 2000)); }
async function doit() { await wait(); console.log('waited'); }
doit(); console.log('the end');

将导致:

the end
waited

但是:

await doit(); console.log('the end');

会做你想做的事,即:

waited
the end

最新更新