Home » Javascript » How do the Promises work in this code?

How do the Promises work in this code?

Posted by: admin June 30, 2018 Leave a comment

Questions:

I have a couple questions about the below code:

  • getRemoteProfile returns Promise.resolve only for one condition but getRemoteProfile calls are always chained with then, so what happens when that condition fails?
  • What’s the difference between return promise and return
    promise.resolve
    , I think return promise.resolve always fall into
    then

    function getRemoteProfile(id) {
        if (!id && /^_/.test(id)) {
            return Promise.resolve(null);
        }
        var isGroup = app.isGroupId(id);
        if (isGroup) {
            return getGroupInfo(id);
        } else {
            return getUserInfo(id.split('@')[0], app.currentUserDomain);
        }
    }
    
    function reloadProfile(id, keep) {
        return getRemoteProfile(id).then(function(contactProfile) {
            // var isGroup = app.isGroupId(id);
            if (contactProfile) {
                contactProfile.contact_id = id;
                if (!keep) {
                    delete profilePromises[id];
                }
                contactProfile.member = true;
                updateProfile(contactProfile.contact_id, contactProfile).then(function() {
                    app.imagesStorage.setContactIcon(contactProfile.contact_id);
                });
    
                return setDetails(contactProfile);
            }
        });
    }
    
Answers: