我正在尝试验证我页面上的各种元素及其数据。我有 3 种不同的方法来完成验证,其中一些方法进行 ajax 调用。每个返回一个 bool 值的 promise 。我想将结果组合成一个变量。我认为以下代码工作正常,但我的 isValid
变量似乎只捕获最后调用的验证函数 saveCurrentSource()
的值。如何让 isValid
等于 saveSourceResponse()
的结果 && validateSource()
&& saveCurrentSource()
?
async validate() {
return new Promise(resolve => {
let isValid = this.saveSourceResponse()
.then(saveSourceResponse => {
console.log("saveSourceResponse",saveSourceResponse);
return this.validateSource();
}).then(validateSourceResponse => {
console.log("validateSourceResponse",validateSourceResponse);
return this.saveCurrentSource(validateSourceResponse);
}).then(saveCurrentSourceResponse => {
console.log("saveCurrentSourceResponse",saveCurrentSourceResponse);
return saveCurrentSourceResponse;
});
resolve(isValid);
});
}
最佳答案
首先,如果您使用的是 async
方法,则根本不需要直接访问 promise,只需使用 await
:
async validate() {
return (
await this.saveSourceResponse() &&
await this.validateSource() &&
await this.saveCurrentSource()
);
}
(我还在下面添加了一个并行版本。)
(我假设 saveCurrentSource
实际上不需要您传递给它的参数。)
如果您确实想要访问 promise (例如,不在validate
上使用async
),您可以使用&&
在每个 then
处理程序中——并且不会使用 new Promise
,因为没有理由:
validate() {
return this.saveSourceResponse()
.then(isValid => isValid && this.validateSource())
.then(isValid => isValid && this.saveCurrentSource());
}
如果我对 saveCurrentSource
的假设不正确,我们会相应地调整它们:
async validate() {
return (
await this.saveSourceResponse() &&
await this.validateSource() &&
await this.saveCurrentSource(true) // `true` because this won't get executed
// if `this.validateSource()` resolves
// to `false`
);
}
或者:
validate() {
return this.saveSourceResponse()
.then(isValid => isValid && this.validateSource())
.then(isValid => isValid && this.saveCurrentSource(true)); // `true` again,
// see above
}
作为Sescudero points out ,如果那些可以并行运行,我们应该并行运行它们:
async validate() {
const results = await Promise.all([
this.saveSourceResponse(),
this.validateSource(),
this.saveCurrentSource()
]);
return results.every(valid => valid);
}
...如果不使用 async
,这非常相似:
validate() {
return Promise.all([
this.saveSourceResponse(),
this.validateSource(),
this.saveCurrentSource()
]).then(results => results.every(valid => valid));
}
关于javascript - 如何将多个 JS promise 链接到组合的 bool 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51674504/