javascript return new Promise:短语法 [英] javascript return new Promise: short syntax

查看:1760
本文介绍了javascript return new Promise:短语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用异步javascript时,第二个函数看起来像这样:

When working with asynchronious javascript every second function looks like this:

function_name()
{
    return new Promise((resolve,reject) => {
       // do some async task
       resolve();
    });
}

即使使用es6 async / await,我也无法避免返回新的Promise( (resolve,reject)=> {...。

Even with es6 async/await I cannot avoid the part "return new Promise((resolve,reject) => { ...".

还有没有其他重复行的编写这种代码的方法吗?

Is there another way of writing such code without all those duplicated lines?

谢谢。

推荐答案

首先,您应该避免使用承诺性反模式,它围绕其他功能带来了新的希望如果您这样做了,那么您可以完全停止执行该操作,而只返回异步操作已经创建的promise。这将立即简化操作。

First off, you should be avoiding the promise anti-pattern that wraps a new promise around other functions that already return promises. If you're doing that, then you can just stop doing that entirely and just return the promise that is already being created by your async operation. That will immediately simplify things.

如果您有一些尚未实现的基于回调的较旧样式的操作,则通常应只对一次基本异步函数进行承诺,然后仅使用返回promise的函数版本进行编码。 zh_cn,您的所有逻辑流程都使用了Promise,在常规代码流中您不会看到 new Promise(...)样板。

If you have older style callback-based operations that are not promisified, then in general, you should promisify the base async function just once and then code only with the version of the function that returns a promise. Then, all your logic flow is using promises and you won't see the new Promise(...) boilerplate in the regular flow of your code.

此外,这些天通常可以避免手动添加。如果您使用的是node.js,则可以使用 util.promisify()创建遵循node.js调用约定的任何异步函数的承诺版本。

Further, you can generally avoid manually promisifying these days. If you're using node.js, then util.promisify() can be used to create a promisified version of any async function following the node.js calling convention.

或者,如果您使用Bluebird Promise库,则可以使用 Promise.promisify()来实现单个函数的实现,或者您可以使用 Promise.promisifyAll()来扩展整个接口。

Or, if you use the Bluebird promise library, you can either promisify an individual function with Promise.promisify() or you can promisify an entire interface with Promise.promisifyAll().

使用这些替代方法之一可以避免样板您会反对。

Using any of these alternate methods avoid the boilerplate you see to be objecting to.

但是,如果您要自己从头手动实现每个功能,而不使用其他任何帮助功能,则有无法避免 new Promise(...)语法。就是这样。

But, if you're going to manually promisify each function from scratch yourself and not use any of these other helper functions, then there is no way to avoid the new Promise(...) syntax. That's what it takes.

因此,您的大多数编码都不应涉及 new Promise(。 ..)。如果确实如此,那么您需要向我们展示一些示例,我们可以为您提供更好/不同的编码方式的建议。

So, most of your coding should NOT involve new Promise(...). If it does, then you need to show us some of your examples and we can advise, better/different ways to code.

这篇关于javascript return new Promise:短语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆