如何避免使用Promise嵌套回调的结构?[完成的] [英] How to avoid nesting structure of callbacks with promises? [finished]

查看:40
本文介绍了如何避免使用Promise嵌套回调的结构?[完成的]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Promise以避免由回调创建的嵌套结构.

I am using promises to avoid the nesting structure created by callbacks.

但是在这段代码中,我仍然有一些嵌套.我在做错什么吗?还是在这种情况下这是不可避免的?

However in this code I still have some nesting. Is there something I am doing wrong or is this un-avoidable in this case?

在这种情况下,我想检查一个配置文件是否存在,是否不想要创建它.

In this case I want to check and see if a profile exists and if it does not I want to create it.

  DB.getProfile(id_google).then((resGet) => {
    if(!resGet[0]){
      console.log('PROFILE - NOT FOUND - MUST CREATE');

      DB.createProfile(id_google, email, name, pic_url).then((resCreate)=>{
        console.log('PROFILE CREATED');
      }).catch((error) => {
        console.log('ERROR - createProfile() Failed: ', error);
      });

    } else {
      console.log('PROFILE FOUND LOCALLY');
      console.log(resGet[0]);
      return done(null, resGet[0])
    }
  }).catch((error) => {
      console.log('ERROR - getOrCreateProfile() Failed: ', error);
  });
};

推荐答案

您可以使用多个 then

DB.getProfile(id_google)
    .then((resGet) => {
        if (!resGot[0]) {
            return DB.createProfile(id_google, email, name, pic_url);
        }
        return resGot[0];
    })
    .then((res) => {
        callback(null, res)
    })
    .catch((error) => {
        console.log('ERROR - getOrCreateProfile() Failed: ', error);
    });

如果存在 resGot [0] ,则将其返回,并且在第二个 then 中,变量 res 是该值.如果没有,则返回 createProfile 的承诺,并且 res 的值就是该函数返回的值

If resGot[0] exist, then it is returned, and in the second then the variable res is that value. If it does not, then the promise of createProfile is returned and the value of res is whatever that function returns

这篇关于如何避免使用Promise嵌套回调的结构?[完成的]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆