为什么以及何时使用 Promise.resolve? [英] Why and when to use Promise.resolve?

查看:57
本文介绍了为什么以及何时使用 Promise.resolve?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,Promise 用于表示异步操作的成功/失败.当我查看我的一个项目时,所有函数都将最终结果包装在Promise.resolve"中.我不明白,将所有函数结果包装在Promise.resolve"中有什么用.这里有任何用例吗?

As I know, Promises are used to represent success/failure of an asynchronous operation. When I am looking into one of my project, all the functions are wrapping the final result in 'Promise.resolve'. I am not understanding, what is the use of wrapping all the function results in 'Promise.resolve'. Is there any use case here?

例如,所有功能都遵循以下模板.

For example, all the functions are following below template.

process = (data) => {
  //Perform some operations.
  return Promise.resolve(result);
} 

推荐答案

使用 Promise.resolve 的唯一原因是将可能承诺的值转换为承诺.

The only reason to use Promise.resolve is converting a value that might be a promise to a promise.

Promise.resolve(value) 是一个方便的方法,它执行 new Promise(resolve => resolve(value).如果值是一个承诺,它将是返回,如果它是来自用户空间承诺库的承诺,它将被转换为原生承诺.如果它是一个普通值,它将被转换为用该值实现的承诺.

Promise.resolve(value) is a convenience method that does new Promise(resolve => resolve(value). If the value is a promise it will be returned, if it is a promise from a userland promise library it will be converted to a native promise. If it is a plain value it will be converted for a promise fulfilled with that value.

Promise.resolve(5); // returns a promise fulfilled with the number 5.

这在多种情况下很有用,例如:- 如果一个函数可能返回一个promise,它应该总是返回一个promise——例如,如果你有一个缓存的值,它可能需要Promise.resolved.- 如果有多个功能实现并且有些是同步的 - 它会创建一个统一的接口.

This is useful in several cases, for example: - If a function might return a promise, it should always return a promise - so for example if you have a cached value it might need to be Promise.resolved. - If there are multiple implementations of functionality and some are synchronous - it creates a uniform interface.

请注意,在使用 async 函数的实践中,这不再需要了,因为 async 函数总是返回一个 promise - 即使您 return 一个普通值(实际上,无论你从异步函数返回什么都是 Promise.resolved 隐式).

Note that in practice with async functions this is not needed so much anymore since an async function always returns a promise - even if you return a plain value (in fact, whatever you return from an async function is Promise.resolved implicitly).

另请注意,特别是如果函数所做的只是同步计算,则不应让函数返回承诺,因为返回承诺的函数意味着 JavaScript 中的 I/O.

Also note that in particular you shouldn't make functions return promises if all they do is synchronous computation since a function returning a promise implies I/O in JavaScript.

这篇关于为什么以及何时使用 Promise.resolve?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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