Javascript 承诺解决得太早
我有一个问题,我的承诺。一切都解决得太早了。对于一个测试,我想console.log数组的长度,该数组从promise映射中推出,但返回0。我相信这很简单Javascript 承诺解决得太早,javascript,node.js,promise,Javascript,Node.js,Promise,我有一个问题,我的承诺。一切都解决得太早了。对于一个测试,我想console.log数组的长度,该数组从promise映射中推出,但返回0。我相信这很简单 fromPath(job.data.path, { density: 100, format: "png" }).bulk(-1, true).then(output => { Promise.all(output.map(page => jimp.read(Buffer.from(page.ba
fromPath(job.data.path, { density: 100, format: "png" }).bulk(-1, true).then(output => {
Promise.all(output.map(page =>
jimp.read(Buffer.from(page.base64, 'base64')).then(img =>
{
img.invert().getBase64Async(jimp.AUTO).then(data => imageArray.push(data.replace('data:image/png;base64,', ''))).catch(err => console.log(err))
}
).catch(err => console.log(err))
)).catch(err => console.log(err))
}
// This returns early
).then(console.log(imageArray.length)).then(done()).catch(err => console.log(err));
任何帮助都将不胜感激。这里有很多问题。主要分为以下几类:
- 不从履行处理程序返回承诺链的结果,这意味着履行处理程序所在的链不会链接到您在其中创建的承诺链
- 调用函数并将其返回值传递到
,而不是将函数传递到然后
然后
fromPath(job.data.path, { density: 100, format: "png" }).bulk(-1, true)
.then(output => {
// Return the result of `Promise.all`
return Promise.all(
output.map(
page => jimp.read(Buffer.from(page.base64, 'base64'))
.then(img => {
// Return the ersult of this promise chain
return img.invert().getBase64Async(jimp.AUTO)
.then(data => imageArray.push(data.replace('data:image/png;base64,', '')))
// This error handler does nothing useful, since we now return
// the promise chain
// .catch(err => console.log(err))
})
// Recommend **not** handling errors at this level, but using
// `Promise.allSettled` instead
.catch(err => console.log(err))
)
)
// This will only be reached if a *synchronous* error occurs calling (for instance)
// `getBase64Async`, since you've already caught errors above
.catch(err => console.log(err))
})
// Use a function here, don't call `console.log` directly
.then(() => console.log(imageArray.length))
// ^^^^^^
// Pass `done` directly to `then`, don't call it and pass its return value
// (e.g., remove the `()`)
.then(done) // Or `.then(() => done)` if you want `done` called with no arguments
.catch(err => console.log(err));
不过,如果我不必使用async
函数,我可能会这样做:
fromPath(job.data.path, { density: 100, format: "png" }).bulk(-1, true)
.then(output => Promise.allSettled(
output.map(
page => jimp.read(Buffer.from(page.base64, 'base64'))
.then(img => img.invert().getBase64Async(jimp.AUTO))
.then(data => {
imageArray.push(data.replace('data:image/png;base64,', ''));
})
)
))
.then(results => {
// Show errors
const errors = results.filter(({status}) => status === "rejected");
for (const {reason} of errors) {
console.error(reason);
}
// Done
done();
});
您的
然后
回调不会返回任何内容。您应该返回Promise.all()
,并且应该返回img.invert()…
这是一个打字错误。您忘记了从中的img.invert().getBase64Async
返回承诺。然后它在处理程序中,因此来自的承诺不会等待来自getBase64Async
的承诺。(还有上面的Promise.all,直接调用console.log
,并将其返回值传递到。然后,
,以及……)嗨,TJ,非常感谢您的帮助和详细的评论!你是个明星。回复:内联格式和阅读承诺,都是一项正在进行的工作,我的朋友。再次感谢。@Tobboulton-:-)很高兴这有帮助。我添加了第二个版本,可能会很有用。快乐编码!