如何避免使用promises嵌套回调结构? [结束]

时间:2017-12-21 04:26:20

标签: javascript express promise passport.js

我使用promises来避免回调创建的嵌套结构。

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

在这种情况下,我想检查并查看是否存在配置文件,如果不存在,我想创建它。

$client = new GuzzleHttp\Client();

$response = $client->request("GET", "http://www.googleapi.com", ['headers' => ['Accept' => 'application/json']]); 

$response_data = json_decode((string) $response->getBody(), true);

return collect($response_data);

2 个答案:

答案 0 :(得分:3)

您可以使用多个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的值是该函数返回的值

答案 1 :(得分:0)

有时将代码简化为基本功能会有所帮助:

getProfile
  if not found, 
    createProfile
       return profile
  else
    done profile

据推测,您希望将createProfile置于与承诺的其余部分相同的链中。

我将结构更改为:

getProfile
  if found, return profile 
  createProfile
    return profile
then
  done(profile)

在这种情况下,实际上不可能只有一个嵌套度。但是你可以减少一定程度的嵌套。

DB.getProfile(id_google)
.then((resGet) => {
    if(resGet[0]) {
      console.log('PROFILE FOUND LOCALLY');
      return resGet[0];
    }
    console.log('PROFILE - NOT FOUND - MUST CREATE');
    return DB.createProfile(id_google, email, name, pic_url)
    .then((resCreate)=>{
      console.log('PROFILE CREATED');
      return resCreate[0]; //Assuming resCreate looks like resGet
    })
  }
})
.then(profile=> {
    //The done function which belongs to passport is called once here.
    console.log(profile);
    return done(null, resGet[0])
})
.catch((error) => {
    console.log('ERROR - getOrCreateProfile() Failed: ', error);
});