Javascript Meteor.call with wait/promise不';似乎不同步

Javascript Meteor.call with wait/promise不';似乎不同步,javascript,meteor,Javascript,Meteor,我一直在尝试以同步方式调用meteor.call。我试着仿效书中给出的例子,但似乎不起作用 const callWithPromise = (method, myParameters) => { return new Promise((resolve, reject) => { Meteor.call(method, myParameters, (err, res) => { if (err) reject('Something went wron

我一直在尝试以同步方式调用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);
     });
  });
 }
下面的函数diid不等待上述操作,调用后立即返回
doStuff()

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

以上的任何输入都是值得赞赏的。

正如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

正如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

是的,
wait
并不能完全满足您的期望。然后它需要包含在一个要使用的
async
函数中:(它仍然在处理承诺,您需要意识到这一点

然而,Meteor确实提供了一个Promise实现,它允许用户无需在异步函数中等待

import { Promise } from 'meteor/promise'
在代码中,您可以执行以下操作:

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

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

是的,
wait
并不能完全满足您的期望(或需要)。然后它需要包含在要使用的
async
函数中:(它仍在处理承诺,你需要意识到这一点

然而,Meteor确实提供了一个Promise实现,它允许用户无需在异步函数中等待

import { Promise } from 'meteor/promise'
在代码中,您可以执行以下操作:

const result = Promise.await(Metor.call('server-method',params))
result
然后包含Meteor方法返回的任何内容,因此它的行为类似于常规函数调用。

你所说的“调用后立即返回”是什么意思?它立即返回承诺,对吗?你所说的“调用后立即返回”是什么意思?它立即返回承诺,对吗?