How do you return promises from functions that prevent returning values ​​without using pending APIs?

I asked a few days ago a promise wraps in the promise of an anti-pattern? that led me to this.

In this case, I had to deal with setTimeoutwhich does not allow returning values. Fortunately, you can handle this using the built-in function delay(at least for bluebird promises).

But what about tasks like gulp? Also inspired by another question: How to transfer an object from gulpfile to another JavaScript file in nodejs?

var stuff;
gulp.task('LoadYamlFiles', function() {
  // do stuff
  stuff = 'blah';
});

module.exports = { stuff };

The export will not be "blah" because the gulp task runs asynchronously. This can be solved using promises.

One way to do this is to use deferred ( https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns code ):

// setTimeout that returns a promise
function delay(ms) {
    var deferred = Promise.pending();
    setTimeout(function(){
        deferred.resolve();
    }, ms);
    return deferred.promise;
}

And this is not actually considered an anti-pattern according to their wiki, but I see that the use is deferredvery discouraged. This seems important for confirmation, because bluebird does not yet have a method .pending()in its API anymore, which means that I cannot do it this way even if I wanted to.

However, you cannot do:

var stuff;
var myPromise = gulp.task('LoadYamlFiles', function() {
  return new Promise(function(resolve, reject) {
    // do stuff
    stuff = 'blah';
    resolve(stuff);
  })
});

module.exports = { myPromise };

because the return value of an anonymous function is not what it will contain myPromise. In addition, this will cause problems that you can see here. Is the gulp task set?

So, how do you deal with these cases when you usually use a de facto outdated template deferred?

+2
1

myPromise, , , =, . ,

var myPromise = new Promise((resolve, reject) => {
  // todo
});

module.exports { myPromise };

.

var myPromise = new Promise((resolve, reject) => {
  gulp.task('LoadYamlFiles', function() {
    let stuff = 'blah';
    resolve(stuff);
  });
});

let myPromise = new Promise(resolve => 
  gulp.task('LoadYamlFiles', () => resolve('blah')));

, , , .

:

+4

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


All Articles