【发布时间】:2020-06-26 18:13:01
【问题描述】:
我有一个以保存文件列表结尾的承诺链。我想等到所有文件都保存或失败,然后继续我的链。问题是,当我在具有自己的子链的 Promise 列表中使用 Promise.all 时,Promise.all 上的 thens 在 Promise.all 内的 Promise 上的 thens 之前开始解决.请参阅下面的注释示例。
const fs = require('fs');
const util = require('util');
// Make a promise out of the file write function
const promiseWriteFile = (file, data, options) => {
return util.promisify(fs.writeFile).call(fs, file, data, options);
};
...
console.log('Received files');
console.group();
// Start long promise chain
somePromise(...)
.then((result) => {
console.log('validating blah blah');
})
.then((result) => {
...
})
.then((result) => {
// Now I need to save the files to the disk
let path = './uploaded_files/';
// Here I want to resolve all the file save promises, or find one that fails
return Promise.all(
request.files.map((file) => {
let filename = path + Date.now() + '_' + file.originalname;
// Purposely change `path` so that the next file write will fail
path = './garbage/';
console.log('Trying to save file:', filename);
return promiseWriteFile(filename, file.buffer, 'binary')
.then(() => {
console.log('Saving file:', filename);
})
.catch((error) => {
console.log('Could not save file:', filename);
throw error;
});
}),
);
})
.then(() => { // <======= I don't want this to happen until the promises in the `Promise.all` above have fully, DEEPLY resolved
// set success message
message = 'Part successfully created.';
console.groupEnd();
console.log('Part created successfully.');
})
.catch((exception) => {
message = exception.message;
console.groupEnd();
console.log('Part invalid.');
});
输出如下:
Received files
validating blah blah
Trying to save file: ./uploaded_files/A.txt
Trying to save file: ./garbage/B.txt
Part invalid.
Could not save file: ./garbage/B.txt
Saving file: ./uploaded_files/A.txt
如您所见,打印“无法保存文件”和“保存文件”的行在大承诺链的 then/catch 之后执行。你可以知道,因为console.groupEnd()首先被调用,然后有进一步的输出。
如何确保在所有子 Promise 都完成之前,大 Promise 链上的 then/catch 不会发生?
【问题讨论】:
标签: javascript promise