我想在Apache Cordova File插件中提供一个方法,但是“ this”存在问题。

最初,我使用的是箭头功能,但是当出现“ this”问题时,我将其删除了。

    /**
     * @param {Function} funcToPromisify -
     * @param {*} firstArgForFuncToPromisify -
     * @returns {Promise<any>} -
     */
    const promisifyFunctionOne = function(funcToPromisify, firstArgForFuncToPromisify) {
        return new Promise(function (resolve, reject) {
            funcToPromisify(firstArgForFuncToPromisify, resolve, reject);
        });
    };


    /**
     * @param {Function} funcToPromisify -
     * @returns {Promise<any>} -
     */
    const promisifyFunctionTwo = function(funcToPromisify) {
        return new Promise(function(resolve, reject) {
                funcToPromisify(resolve, reject);
            }
        );
    };


    /**
     * @param {string} pathToFile -
     * @param {Function} urlResolverFunc -
     * @param {object} stateObj -
     * @returns {void} -
     */
    const readFile = async function(pathToFile, urlResolverFunc) {
        const fileEntry = await promisifyFunctionOne(urlResolverFunc, pathToFile);
        console.log(fileEntry);
        try {
            const fileObj = await promisifyFunctionTwo(fileEntry.file);
            let reader = new FileReader();
            reader.onloadend = function() {
                console.log('Successful file read: ' + this.result);
            };
            reader.readAsText(fileObj);
        }
        catch(error) {
            console.log(error);
        }
    };

    // Example of how readFile() is being called.
    readFile(pathToFile, window.resolveLocalFileSystemURL);




我希望能够推广函数FileEntry.file(),但是我
尝试此操作时收到此错误:TypeError:this.toInternalURL不是FileEntry.file的函数(FileEntry.js:82)

可以在这里查看该代码:https://github.com/apache/cordova-plugin-file/blob/74a46467a081a87bb69b3f2518cbb1db5375028f/www/FileEntry.js#L80

最佳答案

定义promisify时可以使用箭头功能。这是一个不依赖于上下文(this)的基本示例-



const promisify = (f) =>
  (...a) => new Promise ((res, rej) => f (...a, res, rej))

const basic = (a, b, c, success, failure) =>
  c === 0
    ? failure (Error("c cannot be zero"))
    : success (a + b + c)

promisify(basic)(1, 2, 3).then(console.log, console.error)
// 6

promisify(basic)(1, 2, 0).then(console.log, console.error)
// Error: "c cannot be zero"





现在,对于需要上下文的函数,请观察我们如何使用.bind保留上下文-



const promisify = (f) =>
  (...a) => new Promise ((res, rej) => f (...a, res, rej))

const account =
  { balance: 100
  , withdraw: function (amount, success, failure)
    { if (amount > this.balance)
        failure(Error("insufficient funds"))
      else
        (this.balance -= amount, success(this))
    }
  }

const withdraw =
  promisify(account.withdraw.bind(account))

withdraw(35).then(console.log, console.error)
// { balance: 65, withdraw: fn... }

withdraw(9999).then(console.log, console.error)
// Error: "insufficient funds"







请注意,这与节点样式promisify不同,后者的异步函数仅接受一(1)个回调,并且错误始终作为回调的第一个参数传递-



const promisify = f =>
  (...a) => new Promise ((res, rej) =>
    f (...a, (e, x) =>
      e ? rej(e) : res(x)
    )
  )

const divide = (a, b, nodeCallback) =>
  b === 0
    ? nodeCallback(Error("cannot divide by zero"))
    : nodeCallback(null, a/b)

const pdivide =
  promisify(divide)

pdivide(10,2).then(console.log, console.error)
// 5

pdivide(10,0).then(console.log, console.error)
// Error: "cannot divide by zero"





注意,此最后一个片段中定义的promisify随Node一起包含为util.promisify

关于javascript - 如何推广Cordova File插件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57010391/

10-09 22:21