How to construct a Bluebird promise that returns a

2019-03-05 12:11发布

问题:

If I have something like this

return this.retrieveArticles(blogId).then(function(response){
    return response.articles;
  }).then(_).call("findWhere", match).then(function(article){
    return {
      "article": article
    }
  });

and I decide to chop the top bit off

    return response.articles;
  }).then(_).call("findWhere", match).then(function(article){
    return {
      "article": article
    }
  });

How do I do something like

Promise.return(articles).then(_).call("findWhere", match).then(function(article){
    return {
      "article": article
    }
  });

回答1:

Promise.resolve(_(articles)).call("findWhere", match);

or

Promise.resolve(articles).then(_).call("findWhere", match);


回答2:

From then you can directly return value:

var p = someFn().then(function(){
    return 43;
});
p.then(function(val){
    console.log(val); // 42
});

If you're not in a chain you can use Promise.resolve:

 var p = Promise.resolve(42);

 p.then(function(val){
     console.log(val); // 42
 });

Most libraries offer variants of these. Another example is Bluebird - in bluebird you can use Promise.method to force a function to return a promise regardless of whether or not you're returning a value or a promise yourself.



回答3:

function promiseString(str){
  return new Promise(function(resolve, reject) {
    return resolve(str)
  })
}

promiseString("hello world").then(function(x){
  console.log(x)
}