本文介绍了javascript:async/await-传播需要整个呼叫链吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个小的辅助函数上包装了一个将诺言返回到async函数中的函数...

I am wrapping a function returning a promises into an async function on a small helper function...

trash(filesArray, {
    glob: false
})
.then(() => {
    resolve(true);
}).catch((err) =>  {
    return err;
})

...因为我想在更高级别上使用await同步使用它:

…because I like to use it synchronous using the await on the next-higher level:

async empty(liveMode, force) {
    …
    await helpers.trashSync(trashFiles);
    // then doing further stuff...
}

当然,这意味着我需要再次使用async关键字...(否则,我会被告知await是未知保留"字等),如果我没有记错,我会现在需要在下一个更高级别上再次使用await?

Of course, this means, that I need to use the async keyword again... (otherwise I am told await is an ‘unknown reserved’ word or such) and if I am not mistaken, I will now need to use await again on the next-higher level?

await memberSet.empty(true, false)

这个游戏"是否会一直持续到整个应用程序,所以到最后,无论哪里有一个很小的异步功能,我都有很多async/await?

Does this "game" continue all the way up and throughout my application, so by the end, I have plenty of async/await's wherever there's a tiny async function contained?

还是我只是错过了停止的地方?

推荐答案

您不能将异步函数转换为同步函数,异步/等待的目的是允许您编写具有与之相似的代码路径的代码.同步调用,但允许重新进入事件循环,因此更加精细.生成器/产量是中断执行流程的另一种方法.

You can't convert an async function into a sync function, the purpose of async/await is to allow you to write code that has a similar code path to synchronous calls, but allowing the event loop to be re-entrant and therefore more fine grained. Generator/yield is an alternative approach to interrupting flow of execution.

您将需要找到一个点,您的调用堆栈自然会期望返回承诺,或者不在乎它是异步完成的.

You'll need to find a point where your call stack naturally expects a returned promise, or doesn't care that it completes asynchronously.

这篇关于javascript:async/await-传播需要整个呼叫链吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:53