属性'value'"/>
UnhandledPromiseRejectionWarning:TypeError:无法设置未定义的属性'value'
我是JS的新手,并尝试了解我在代码中使用的Promise模块。下面是代码[1],在其中我试图通过提供几个value参数选项使它以某种方式运行,实际上我希望将其设置为cipher.encrypt(IP)(提供保留加密的格式) IP,例如:cipher.encrypt(15.10.23.4)= 20.24.35.9)。我收到的错误如下:
(node:9964) UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'value' of undefined
at cache.<computed>.promise (/home/pooja/Documents/weiterbildung/promises/simple.js:13:23)
at new Promise (<anonymous>)
at doEncryption (/home/pooja/Documents/weiterbildung/promises/simple.js:8:15)
at Object.<anonymous> (/home/pooja/Documents/weiterbildung/promises/simple.js:29:12)
at Module._compile (internal/modules/cjs/loader.js:1176:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1196:10)
at Module.load (internal/modules/cjs/loader.js:1040:32)
at Function.Module._load (internal/modules/cjs/loader.js:929:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
谢谢,
[1]
const crypto = require('./fpe');
const cipher = crypto({});
const cache = {};
function doEncryption(IP) {
if (!cache[IP]) {
cache[IP] = {
promise: new Promise((resolve, reject) => {
if(cipher.encrypt(IP)) {
const value = "" + 10; // const value = cipher.encrypt(IP)
cache[IP].value = value;
resolve(value);
}
else {
resolve([]);
}
}), //end of promise
};
return cache[IP].promise;
} else if (!cache[IP].value) {
return cache[IP].promise;
}
return Promise.resolve(cache[IP].value);
}
IP = "10.10.10.10"
let temp = doEncryption(IP)
temp.then(value => console.log(value))
回答如下:cache[IP]
在promise中尚不存在。此外,您的代码将不起作用,因为您仅将Promise(不带cache[IP]
)分配给value
一个新对象。
一种简单的解决方法,虽然可能不是最好的,但可能是:
cache[IP] = {}
cache[IP].promise = ...
更多推荐
UnhandledPromiseRejectionWarning:TypeError:无法设置未定义的属性'value'
发布评论