javascript - 在 Promise.prototype.then() 外部声明的对象在其内部使用时返回 undefined

标签 javascript

在下面的函数中,我遇到了一个问题,即 options 在 .then() 中被认为是未定义的,即使 console.log(options.destination)storageObj 函数调用链正确打印之前。

/**
 * Returns a promise that resolves an object including the
 * file destination if the requested file is downloaded successfully
 * and rejects if there is an error whle downloading the file.
 *
 * @param {Object} storageObj GCS Storage object instance.
 * @param {String} bucketName Name of the bucket to access in the GCS Storage object.
 * @param {String} filePath Path of the file to access in the given bucketName.
 * @param {String} destinationDir Name of the direcory to download the file to.
 * @returns Promise
 */
function downloadGCSFileToDir(storageObj, bucketName, filePath, destinationDir) {
    return new Promise((resolve, reject) => {
        console.log("filePath is: " + filePath);
        const filePathParts = filePath.split("/");
        const destination = `${destinationDir}/${filePathParts[filePathParts.length - 1]}`;
        const options = { "destination": destination };
        console.log(options.destination);
        storageObj
            .bucket(bucketName)
            .file(filePath)
            .download(options)
            .then(() => {
                console.log(`gs://${bucketName}/${filePath} downloaded to ${options.destination}`);
                resolve({ "destination": options.destination });
            })
            .catch(err => reject(new Error(`downloadGCSFileToDir failed: ${err}`)));
    });
}

但是如果我在 .then() 中使用 destination 这样:

function downloadGCSFileToDir(storageObj, bucketName, filePath, destinationDir) {
    return new Promise((resolve, reject) => {
        console.log("filePath is: " + filePath);
        const filePathParts = filePath.split("/");
        const destination = `${destinationDir}/${filePathParts[filePathParts.length - 1]}`;
        const options = { "destination": destination };
        console.log(options.destination);
        storageObj
            .bucket(bucketName)
            .file(filePath)
            .download(options)
            .then(() => {
                console.log(`gs://${bucketName}/${filePath} downloaded to ${destination}`);
                resolve({ "destination": destination });
            })
            .catch(err => reject(new Error(`downloadGCSFileToDir failed: ${err}`)));
    });
}

它按预期打印。这是为什么?

最佳答案

options 在您的 then 中不是未定义的; options.destination 是。原因是 download 方法 deletes the destination property来自 options 对象。

File.prototype.download = function(options, callback) {
  if (is.fn(options)) {
    callback = options;
    options = {};
  }

  callback = once(callback);

  var destination = options.destination;
  delete options.destination;  // <--- here

  // ...

至于它为什么这样做,你的猜测和我的一样好。

关于javascript - 在 Promise.prototype.then() 外部声明的对象在其内部使用时返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48508328/

相关文章:

javascript - 如何使用从 api 获取的 React 组件?

javascript - D3.js geoPath map 返回错误 : <path> attribute d: Expected number

javascript - 是否可以在触发 $stateChangeStart 之前解析某些数据?

javascript - Canvas toBlob 在 iPhone Safari 上不起作用?

javascript - 使用信号器更新数据库更改时如何刷新 View

javascript - Selection::addRange 在大 DOM 中非常慢

JavaScript——类型转换

javascript - 查找带有特定文本的 td,并在该文本之后立即对 td 进行操作?

javascript - 未捕获的类型错误 : Cannot read property '0' of undefined CryptoJS

javascript - 为什么我在进行突变时会收到 "Cannot return null for non-nullable field"错误?