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

时间:2018-01-29 19:08:57

标签: javascript

在以下函数中,即使options函数调用链之前的console.log(options.destination)打印出来,我仍然遇到{.1}}在.then()内被认为是未定义的问题正确。

storageObj

但是如果我在.then()中使用/** * 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}`))); }); }

destination

按预期打印。那是为什么?

1 个答案:

答案 0 :(得分:2)

class AnotherClass { [modifiers(?)] MyClass myObjects; void initFunction( ... ) { // some code myObjects = new MyClass[] { ... }; } MyClass accessFunction(int index) { return myObjects[index]; } } options内未定义; then是。原因是来自options.destination对象的download方法deletes the destination property

options

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