我试图并行运行两个彼此不依赖的异步操作,但我似乎无法让它工作。
const activity = fetchActivity(...)
const progress = fetchProgress(...)
await activity
await progress
当我打印
当我这样运行它时,属性会显示出来。
const activity = await fetchActivity(...)
const progress = await fetchProgress(...)
我在想,并行方法 更新: 因此,显然我无法回答我自己的问题,因为问题已经结束,但我首先要感谢那些指导我找到正确答案的人,尽管他们没有回答我的问题。 虽然下面给出了我的问题的实际解决方案,但是这里给出了不使用这种方法的原因:等待多个并发的await操作,我应该转而追求已经到处提到的解决方案。 答:const activity = fetchActivity(...)
const progress = fetchProgress(...)
const activityData = await activity
const progressData = await progress
方法返回
您可以在解析
如果您选择等待
如果您不想等待结果,您可能更喜欢使用
const res1 = await promise1;
const nextLine = 1+1; // will happen after the promise is resolved
或
promise1.then(res1 => // register callback and do something with the response).
const nextLine = 1+1; // will happen immediately
现在,在您了解了什么是
const fetchActivityPromise = fetchActivity(..)
const fetchProgressPromise = fetchProgress(..)
const promiseRes = Promise.all([fetchActivityPromise, fetchProgressPromise]);
promiseRes.then(r => ...)
console.log('here before the promiseRes.then was called');
您可以转而使用promise.all():
例如:
await Promise.all([call1(), call2()]);
您可以通过以下方式存储结果:
let [res1, res2] = await Promise.all([call1(), call2()]);
希望对你有帮助!