承诺中的承诺:从子承诺中返回变量的正确方法是什么? (JS)

新手上路,请多包涵

我有这样的功能:

 function top() {

  //promise1
  ParentPromise({
    ...some code here...
  }).then(function() {

    //promise2
        ChildPromise({
          ..some code here...
        }).then(function(response) {
         var result = response.result.items;

        });

});

};

我需要以这种方式返回结果值:

 var myresult = start();

我该怎么做?谢谢

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

阅读 271
2 个回答

promises 的定义是你不能按字面意义将 result 分配给 myresult 。 _但是_,您可以为调用者做出 myresult 直接解析为 result 的承诺,但是使用了许多承诺来实现这一点。基本思想是,在上面块中的每个函数内部,您应该 return 链中的下一个 Promise。例如:

 function top() {

  //promise1
  return ParentPromise({
    ...some code here...
  }).then(function() {

    //promise2
        return ChildPromise({
          ..some code here...
        }).then(function(response) {
         var result = response.result.items;
         return result;

        });

});

};

最后,调用 top() 的代码将不知道或不关心使用 1、2 或 12 个链式承诺来获取 result 。如果这些承诺中的任何一个失败,它也将能够注册一个错误回调。

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

在我看来,最巧妙的方法是返回承诺并将它们“向下”链接而不是向左链接,避免圣诞树般的回调地狱。

 function top() {
  //promise1
  return ParentPromise({
    ...some code here...
  }).then(function(parent) {
    //promise2
    return ChildPromise(parent.id)
  }).then(function(response) {
    // do something with `result`

    return response.result.items;
  });
}

top().then(function(items){
  // all done
});

编辑: 或者用 ES6 / lambda 表示法;

 function top() {
  return ParentPromise().then(parent => {
    return ChildPromise(parent.id)
  }).then(response => {
    return response.result.items
  })
}

top().then(items => {
  // all done
})

编辑: 或使用异步/等待;

 async function top() {
  const parent = await ParentPromise()
  const child = await ChildPromise(parent.id)

  return child.result.items
}

top().then(items => {
  // all done
})

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

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