在下面的函数中,我遇到了一个问题,即 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/