【问题标题】:How to construct a Bluebird promise that returns a constant string?如何构造一个返回常量字符串的 Bluebird Promise?
【发布时间】:2015-02-18 06:14:03
【问题描述】:

如果我有这样的事情

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

我决定砍掉顶部的部分

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

我该怎么做

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

【问题讨论】:

  • 你的意思是Promise.resolve(_(articles).findWhere(match))

标签: javascript promise bluebird


【解决方案1】:
Promise.resolve(_(articles)).call("findWhere", match);

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

【讨论】:

    【解决方案2】:

    then可以直接返回值:

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

    如果你不在链中,你可以使用Promise.resolve

     var p = Promise.resolve(42);
    
     p.then(function(val){
         console.log(val); // 42
     });
    

    大多数库都提供这些变体。另一个例子是 Bluebird - 在 bluebird 中,您可以使用 Promise.method 强制函数返回一个 Promise,无论您自己返回的是值还是 Promise。

    【讨论】:

      【解决方案3】:
      function promiseString(str){
        return new Promise(function(resolve, reject) {
          return resolve(str)
        })
      }
      
      promiseString("hello world").then(function(x){
        console.log(x)
      }
      

      【讨论】:

      • 这有点粗鲁。
      猜你喜欢
      • 1970-01-01
      • 2021-05-17
      • 1970-01-01
      • 2012-08-14
      • 2021-01-11
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多