我什么时候应该直接调用Promise.resolve()? [英] When should I call Promise.resolve() directly?

查看:228
本文介绍了我什么时候应该直接调用Promise.resolve()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到,原生ES6 Promise.resolve()可以直接调用 - 作为静态方法。 Facebook在他们的Flux示例中使用它。

I've seen that the native ES6 Promise.resolve() can be invoked directly - as a static method. Facebook is using it that way in their Flux examples.

但在什么情况下我应该这样做?排队的东西?或者不是使用 window.setTimeout()

But in what case should I do that? To queue something? Or instead of using window.setTimeout()?

推荐答案

当您需要创建已解决的承诺时,调用 Promise.resolve(object)。例如,您可能有一个功能,可以从服务器开始下载资源或返回其缓存版本:

You should call Promise.resolve(object) when you need to create a promise that is already resolved. For example you may have a function that starts downloading a resource from the server or returns its cached version:

function getImage(imageUrl) {
    if (imageUrl in this.cache) {
        // no need to download, return immediately
        return Promise.resolve(this.cache[imageUrl]);
    } else {
        return new Promise(function(resolve, reject) {
            // start downloading and eventually resolve
        });
    }
}

这篇关于我什么时候应该直接调用Promise.resolve()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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