diff --git a/src/plugins/plugin.ts b/src/plugins/plugin.ts index ec11b3cd1c..69ee6cc4fe 100644 --- a/src/plugins/plugin.ts +++ b/src/plugins/plugin.ts @@ -65,20 +65,33 @@ function setIndex(args: any[], opts: any = {}, resolve?: Function, reject?: Func obj[opts.errorName] = reject; args.push(obj); } else if (typeof opts.successIndex !== 'undefined' || typeof opts.errorIndex !== 'undefined') { - // If we've specified a success/error index + const setSuccessIndex = () => { + // If we've specified a success/error index + if (opts.successIndex > args.length) { + args[opts.successIndex] = resolve; + } else { + args.splice(opts.successIndex, 0, resolve); + } + }; - if (opts.successIndex > args.length) { - args[opts.successIndex] = resolve; - } else { - args.splice(opts.successIndex, 0, resolve); - } + const setErrorIndex = () => { + // We don't want that the reject cb gets spliced into the position of an optional argument that has not been defined and thus causing non expected behaviour. + if (opts.errorIndex > args.length) { + args[opts.errorIndex] = reject; // insert the reject fn at the correct specific index + } else { + args.splice(opts.errorIndex, 0, reject); // otherwise just splice it into the array + } + }; - // We don't want that the reject cb gets spliced into the position of an optional argument that has not been defined and thus causing non expected behaviour. - if (opts.errorIndex > args.length) { - args[opts.errorIndex] = reject; // insert the reject fn at the correct specific index + if(opts.successIndex > opts.errorIndex) { + setErrorIndex(); + setSuccessIndex(); } else { - args.splice(opts.errorIndex, 0, reject); // otherwise just splice it into the array + setSuccessIndex(); + setErrorIndex(); } + + } else { // Otherwise, let's tack them on to the end of the argument list // which is 90% of cases diff --git a/test/plugin.spec.ts b/test/plugin.spec.ts index ecdb07a744..b808936c09 100644 --- a/test/plugin.spec.ts +++ b/test/plugin.spec.ts @@ -138,4 +138,36 @@ describe('plugin', () => { }); + it('reverse callback at the end of the function', done => { + + window.plugins.test.reverseEndCallback = (args, error, success) => { + success('Success'); + }; + + @Plugin(testPluginMeta) + class Test { + + @Cordova({ + successIndex: 2, + errorIndex: 1 + }) + static reverseEndCallback(args: any): Promise { return; } + + } + + const spy = spyOn(window.plugins.test, 'reverseEndCallback').and.callThrough(); + const cb = (result) => { + expect(result).toEqual('Success'); + done(); + }; + + Test.reverseEndCallback('foo').then(cb, cb); + + expect(spy.calls.mostRecent().args[0]).toEqual('foo'); + expect(spy.calls.mostRecent().args[1]).toBeDefined(); + expect(spy.calls.mostRecent().args[2]).toBeDefined(); + expect(spy.calls.mostRecent().args[3]).toBeUndefined(); + + }); + });