javascript - 如何在执行其余代码之前等待图像下载
问题描述
我希望你一切都好,所以我已经使用 nodejs 一段时间了,我仍然习惯于异步功能和东西,所以我使用 axios 从服务器下载图像,并等待图像下载然后使用图片在wordpress网站上发布帖子,代码有点棘手,因为它可以处理几个帖子,但其他人它不会等待图像完全下载,但它只是分享没有图片的帖子.
axios.get(encodeURI(img), {responseType: "stream"} )
.then(response => {
// Saving file to working directory
response.data.pipe(fs.createWriteStream("images/"+title.replace(/[^\x00-\x7F]/g, "")+".png"));
await sleep(3000);
var wp = new WPAPI({
endpoint: 'XXXXX/wp-json',
// This assumes you are using basic auth, as described further below
username: 'XXXX',
password: 'XXXXX'
});
wp.posts().create({
title: title,
content: index,
categories: [3,9,2],
status: 'publish'
}).then(function( post ) {
// Create the media record & upload your image file
var filePath = "images/"+title.replace(/[^\x00-\x7F]/g, "")+".png";
return wp.media().file( filePath ).create({
title: title,
// This property associates our new media record with our new post:
post: post.id
}).then(function( media ) {
console.log( 'Media uploaded with ID #' + media.id );
return wp.posts().id( post.id ).update({
featured_media: media.id
});
});
});
})
.catch(error => {
console.log(error);
});
所以我问我如何才能完全等到图像存在于文件夹中,然后再分享帖子谢谢。
解决方案
代替
response.data.pipe(fs.createWriteStream("images/"+title.replace(/[^\x00-\x7F]/g, "")+".png"));
await sleep(3000);
利用
response.data.pipe(fs.createWriteStream("images/"+title.replace(/[^\x00-\x7F]/g, "")+".png"))
.on('error', () => {
// log error and process
})
.on('finish', () => {
// publish a post with image on a wordpress website,
});
PS:尝试制作模块化代码,
推荐阅读
- python - 你能扩展 pandas.get_dummies 中的假人列表吗?
- reactjs - 渲染太多模态框会导致问题吗?
- python-3.x - 返回多个值时如何指定函数的返回类型?
- jdbc - Kafka JDBC Sink Connector,批量插入值
- c++ - 我只是在看模板,在我的书中发现了这段代码,这显示了分段错误?
- sinatra - 如何在 Sinatra 中使用 CarrierWave 显示图像
- hdfs - 如何从 Akka Stream 读取 HDFS 文件?
- angular - Angular:ControlValueAccessor vs @Input - 什么时候使用表单?
- excel - Excel 网络自动化:输入无效
- javascript - 单击时访问传单标记元属性