繁体   English   中英

搞砸了吗?

[英]Promises messing up?

在过去的几天里,这个问题一直困扰着我。 我远不是Java语言专家,也许解决方案很明显,但我看不到。

我基本上想做的是:

  1. 以并行方式下载项目,每个请求都针对具有不同属性的给定项目类型(类型1,类型2)。
  2. 下载后,执行回调函数以对数据进行后处理(该函数具有相同的参数,但具有不同的参数,并且需要对项目类型进行测试以进行不同的处理)
  3. 保存物品

如果我下载一种项目类型,则一切正常。 但是,如果我下载了2种类型,那么在第一次回调执行中的处理循环中的某个时间点,正是当第二次针对第二种类型执行第二次回调时,对类型的测试将表明它是第二种类型,而项是第一类的...

以下是代码摘录:

 downloadType1(); downloadType2(); // 2nd argument of download() is the callback function // 3rd argument is the callback function parameters function downloadType1() { // Some stuff here let callbackParameters = ['type1', 'directory1']; download('url', headacheCallback, callbackParameters); } function downloadType2() { // Some the stuff here let callbackParameters = ['type2', 'directory2']; download('url', headacheCallback, callbackParameters); } async function download(url, callbackBeforeSave, callbackParameters) { // Some stuff here let response; try { response = await rp(url); } catch (e) { console.log("Error downloading data"); } // Call callbacks before saving the data if(callbackBeforeSave) { let updatedResponse; if (callbackParameters) { updatedResponse = await callbackBeforeSave(response, ...callbackParameters); } else { updatedResponse = await callbackBeforeSave(response); } response = updatedResponse; } // Some stuff here with the post-processed data } async function headacheCallback(data, type, directory) { for (item of data) { // Some stuff here, include async/await calls (mostly to download and save files) console.log(type, item.propertyToUpdate, item.child.propertyToUpdate); // This is were my issue is. // The test will success although I'm still the 'type1' loop. I know because the console.log above shows the item is indeed of type 'type1' if (type === 'type2') { item.child.propertyToUpdate = newUrl; // Will eventually fail because 'type1' items don't have a .child.propertyToUpdate property } else { item.propertyToUpdate = newUrl; } } } 

在某些时候, console.log的输出将是: type2 <valueOfTheProperty> undefined ,它应该是type2 undefined <valueOfTheProperty> ...

快速思考:在回调的第一个版本中,我将arguments全局变量与function.apply(...)结合使用。 这很糟糕,因为arguments是全局的,因此在第二次调用之后被更改了...

但是现在我看不到代码中的任何全局信息可以解释为什么type在变化。

任何帮助将不胜感激。

谢谢!

我在代码中看不到任何可以解释类型为何更改的全局信息。

不是正在改变的type 你的问题是, item是一个无意识的全球

for (item of data) {
//   ^^^^

使那个

for (const item of data) {
//   ^^^^

并始终启用严格模式!

这是Promise.all的工作

const p1 = new Promise((res, rej) => res());
Promise.all([p1, p2]).then((results) => results.map(yourFunction));

Promise.all将返回已解决的数组,否则可能会拒绝。 但是,如果您使用仅能解决的新Promise设置p1,p2,pn,则不必拒绝。 然后,您的功能图就可以处理分支并为正确的响应类型做正确的事情。 说得通?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM