When should I call Promise.resolve () directly?

I saw that native ES6 Promise.resolve()can be called directly - as a static method. Facebook uses it this way in its Flux examples.

But in which case should I do this? Is something worth it? Or instead window.setTimeout()?

+4
source share
3 answers

You must 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
        });
    }
}
+5
source

Promise.resolve(42) is simply a shorthand for

new Promise(function(resolve) {
    resolve(42);
});

, - , .. , Promise.resolve.

+1

, promises, , , :

a().then(b).then(c).catch(failure);

, , .then , , promises. . b / c , promises, , a , TypeError.

, , , a, , , , a (, ),

Promise.resolve(a()).then(b).then(c).catch(failure);

a, b c :

  • a 1, b 1.
  • a , b a.

Promise.reject .

, , , . .

[a, b, c].reduce((p, f) => p.then(f), Promise.resolve()).catch(failure);
+1

Source: https://habr.com/ru/post/1606441/


All Articles