[英]How can I reference an object value within an array of promises?
The Object below contains lookup keys which contain an Array of Promises used to run a series of validations against a value
. 下面的对象包含含有用于运行一系列针对验证的承诺的阵列查找密钥value
。
How can the value of full_name
be accessible from email
? 如何通过email
访问full_name
的值?
const config = {
full_name: [
val => new Promise((resolve, reject) => resolve(val)),
val => new Promise((resolve, reject) => resolve(val))
],
email: [
val => new Promise((resolve, reject) => resolve(val)),
val => new Promise((resolve, reject) => reject(`${config.full_name.val}`)) // get the value which has been passed to full_name
]
}
config.full_name.val
does not exist, because config.full_name
is an array with functions that return promises. config.full_name.val
不存在,因为config.full_name
是具有返回promise函数的数组。
The use case here depends on the context of how these functions are invoked. 这里的用例取决于如何调用这些功能的上下文。 This context is explained here: https://jsfiddle.net/karlbateman/keqnrybq/ . 此处说明了此上下文: https : //jsfiddle.net/karlbateman/keqnrybq/ 。
Considering also that the validation part lives in a different module than the actual config, one cannot simply access the formData in the callbacks. 还考虑到验证部分与实际配置位于不同的模块中,因此不能简单地在回调中访问formData。
However, you can add a context param to your function callbacks which provides the formData to be accessed, as shown here: https://jsfiddle.net/odolha/tpn75570/ 但是,您可以在函数回调中添加上下文参数,以提供要访问的formData,如下所示: https ://jsfiddle.net/odolha/tpn75570/
See this line (in the validatorFn): 参见以下行(在validatorFn中):
arr.push(config[field].map(cb => cb(formData[field], formData)))
This basically provides the formData as a context param, which can be used later: 这基本上提供了formData作为上下文参数,可以在以后使用:
(val, ctx) => new Promise((resolve, reject) => setTimeout(() => {
reject(`${ctx.name} already is exists.`) // simulate a HTTP request
}, 2000))
You may also implement a similar functionality as follows; 您还可以实现以下类似功能;
function promisifier(val, pass = true){ return new Promise(function(v,x){ return pass ? v(val) : x(val); }); } var config = { full_name: [promisifier, promisifier], email: [promisifier, promisifier] }; config.full_name[0]("Thaddeus Jones") .then(r => config.email[1](r,false)) .then(r => console.log("resolved by:", r)) .catch(e => console.log("received error:", e));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.