在数组映射中使用新的 Promise
Working with new Promise inside a array map
我正在使用具有 3 个阶段的软件:
第一阶段、第二阶段和第三阶段。
在第一阶段我使用 exiftool 从文件中提取元数据,但过程是异步的,所以我需要等待结果才能调用下一阶段,为此,我使用以下代码:
MAP.files = files.scan((file) => {
return new Promise((resolve) => {
exiftool(file, (error, metadata) => {
file.error = error
file.metadata = metadata
resolve(file)
});
});
});
返回的是带有一堆对象的数组,如下所示:
[ Promise { <pending> },
Promise { <pending> },
Promise { <pending> }
.....
]
第二阶段不是异步的,我需要像上一阶段一样访问文件,使用 array.map,如下所示:
MAP.files.text = MAP.files((file) => {
//To be able to access the real file, i need use then, like this:
file.then((realFile) => {
console.log(realFile) // real file with properties
});
});
在下一阶段(第3阶段),我想做同样的事情:
MAP.files.final = MAP.files.text((file) => {
});
我的问题是:THEN 函数,我不能逃避它吗?我需要在第一阶段后的每个阶段使用 file.then 吗??
看起来使用 Promise.all
会对你有所帮助。
例如如果你有一系列的承诺......
var p = [p1, p2, p3]
Promise.all(p).then( (results) =>
/* results is an array of the results of each promise in p */
);
有关 Promise.all
的文档,请参阅 http://bluebirdjs.com/docs/api/promise.all.html and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
我正在使用具有 3 个阶段的软件:
第一阶段、第二阶段和第三阶段。
在第一阶段我使用 exiftool 从文件中提取元数据,但过程是异步的,所以我需要等待结果才能调用下一阶段,为此,我使用以下代码:
MAP.files = files.scan((file) => {
return new Promise((resolve) => {
exiftool(file, (error, metadata) => {
file.error = error
file.metadata = metadata
resolve(file)
});
});
});
返回的是带有一堆对象的数组,如下所示:
[ Promise { <pending> },
Promise { <pending> },
Promise { <pending> }
.....
]
第二阶段不是异步的,我需要像上一阶段一样访问文件,使用 array.map,如下所示:
MAP.files.text = MAP.files((file) => {
//To be able to access the real file, i need use then, like this:
file.then((realFile) => {
console.log(realFile) // real file with properties
});
});
在下一阶段(第3阶段),我想做同样的事情:
MAP.files.final = MAP.files.text((file) => {
});
我的问题是:THEN 函数,我不能逃避它吗?我需要在第一阶段后的每个阶段使用 file.then 吗??
看起来使用 Promise.all
会对你有所帮助。
例如如果你有一系列的承诺......
var p = [p1, p2, p3]
Promise.all(p).then( (results) =>
/* results is an array of the results of each promise in p */
);
有关 Promise.all