我有一个生成
作为child_process
的 Node 应用程序。当 child_process
完成运行时,我想解决一个 promise 。以下代码有效,但 .then()
语句发生顺序不正确:
const storage = require('./storage');
const logging = require('./logging');
const process = require('child_process').spawn;
function convertIncomingFile(pathToFile) {
logging.info(`Converting ${pathToFile}`);
const convert = process(`cat`, [pathToFile], {});
return Promise.resolve(
convert.stdout.on('data', (data) => {
logging.info(data.toString('utf8'));
}),
convert.stderr.on('data', (err) => {
logging.error(err);
}),
convert.on('close', (code) => {
logging.info(`Conversion finished with status code ${code}`);
})
);
}
module.exports = {
convertFile: (filename) => {
storage.downloadFile(filename).
then((localFilename) => {
logging.info(`File saved to: ${localFilename}`);
}).
then(() => convertIncomingFile(`./files/${filename}`)).
then(() => {
logging.info(`Coversion of ${filename} complete.`);
}).
catch((apiErr) => {
logging.error(apiErr);
});
}
};
我得到的输出是:
info: File saved to: ./files/package.json
info: Converting ./files/package.json
info: Coversion of package.json complete.
info: {
<file contents>
}
info: Conversion finished with status code 0
如您所见,Conversion of package.jsoncomplete.
语句发生在记录文件内容和转换状态代码语句之前。为什么会出现这种情况?如何在“状态代码”语句之后出现“转换完成”语句?
最佳答案
Promise.resolve
表示返回您给它的已解决值,它并不像您预期的那样真正异步。检查https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve和 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise了解更多详细信息
function convertIncomingFile(pathToFile) {
logging.info(`Converting ${pathToFile}`);
const convert = process(`cat`, [pathToFile], {});
return new Promise((resolve, reject) => {
convert.stdout.on('data', (data) => {
logging.info(data.toString('utf8'));
}),
convert.stderr.on('data', (err) => {
logging.error(err);
reject()
}),
convert.on('close', (code) => {
logging.info(`Conversion finished with status code ${code}`);
resolve()
})
})
}
关于javascript - 为什么这些 .then() 会乱序发生?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47341628/