如果找到值,则返回解析为布尔值 true 或 false 的承诺

新手上路,请多包涵

我需要进行一个 api 调用,返回一个 id 和与之关联的值的响应。如果找到或未找到所查询的 id,则 promise 会解析并返回 true 或 false。

我怎样才能做到这一点?使用承诺的新手。正如承诺似乎令人困惑

这是使用 API 的终点,UserService 返回一个 id 和薪水数组。我需要检查 id 是否存在以及薪水是否与查询匹配,然后 promise 需要解析为 true 或 false。

这是 id 和收入的对象

      [{
            "id": 1,
            "name": "Primary",
            "sal": [{
                    "id": "1",
                    "sal": "10"
                }, {
                    "id": "2",
                    "sal": "20"
                }]
            },{
            "id": 2,
            "name": "Secondary",
            "sal": [{
                    "id": "1",
                    "sal": "100"
                }, {
                    "id": "2",
                    "sal": "200"
                }
            ]
        }];

  UserService.hasUserValue(id, income).then(function(qualifiesforlowIncome){
     var isLowIncome = qualifiesforlowIncome
   }

qualifiesforlowIncome 是一个返回 true 或 false 的布尔值。我正在使用 angular 所以在这种情况下我应该做一个 $q.defer 并返回一个 defer.promise 吗?

这个有点不清楚

原文由 looneytunes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 209
1 个回答

当然,您需要做的就是添加一个 then 判断是否有任何对象匹配查询的大小写然后返回 truefalse 该值将进入下一个 then 案例。

在此示例中,我使用 some 方法来查看数组中的任何对象是否符合条件。

 Promise.resolve([
    {
      id: 1
    },
    {
      id: 2
    },
    {
      id: 3
    }
  ])
  .then(results =>
    results.some(r => r.id === 2)
  )
  .then(foundResult => console.log(foundResult));

或者用 ES5 重写:

 Promise.resolve([
    {
      id: 1
    },
    {
      id: 2
    },
    {
      id: 3
    }
  ])
  .then(function(results) {
    return results.some(r => r.id === 2);
  })
  .then(function(foundResult) {
    console.log(foundResult);
  });

即使您返回一个稍后解析的 Promise,这也完全相同。

 Promise.resolve([
    {
      id: 1
    },
    {
      id: 2
    },
    {
      id: 3
    }
  ])
  .then(results =>
    // Return a promise, delay sending back the result
    new Promise((resolve, reject) => {
      setTimeout(() =>
        resolve(results.some(r => r.id === 2)),
        500
      );
    })
  )
  .then(foundResult => console.log(foundResult));

原文由 Mike Cluck 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题