[Promise] How can I return a Promise?


#1

Hi guys, I am facing this problem with a Promise, I want to return a promise when I select one picture from Gallery using ImagePicker plugin, and then work with the file.

This is my code:

takePictureFromGallery() : any {
        let context = imagepicker.create({
            mode: "single"
        });
        context
            .authorize()
            .then(function() {
                return context.present();
            })
            .then(function(selection) {
                selection.forEach(function(selected) {
                    dialogs.prompt({
                        title: Globals.APP_NAME,
                        message: "Picture description (optional)",
                        okButtonText: "OK",
                        cancelButtonText: "Cancel",
                        inputType: dialogs.inputType.text
                    }).then(r => {
                        if (r.result) {
                            parameters.Headers['Description'] = "";
                            if (r.text != '') parameters.Headers['Description'] = r.text;
                        }
                        let imageSource = new imageSourceModule.ImageSource();
                        imageSource.fromAsset(selected).then((source) => {
                            let savepath = fileSystem.knownFolders.documents().path;
                            let filename = 'img_' + new Date().getTime() + '.' + "jpg";
                            let filepath = fileSystem.path.join(savepath, filename);
                            
                            var picSaved = source.saveToFile(filepath, "jpg");

                            return new Promise((resolve, reject) => {
                                if (picSaved) resolve(filepath);
                                else reject();
                            });
                            
                        })
                    })
                })
            }).catch(function (e) {
                this._feedback.error({message: "You must allow " + Globals.APP_NAME + " access to your Gallery"});
            });
        
    }

This method belongs to a class called PictureUploader. Outside this class I have this code:

let pu = new PictureUploader();
pu.takePictureFromGallery()
    .then(s => {
        console.log(s);
})

I get undefined is not an object when I try to run the .then() method.

Any help? Thanks!


#2

You forgot the return.

...
return context
            .authorize()
...