如何在执行其余代码之前等待图像下载

How to wait for image to download before executing the rest of the code

我希望你一切都好,所以我使用 nodejs 已经有一段时间了,我仍然习惯异步函数和东西,所以我使用 axios 从服务器下载图像,并等待图片下载,然后使用图片在 wordpress 网站上发布 post,代码有点棘手,因为它可以工作几个 post,但其他人不会等待图片完全下载,但是它只分享 post 而没有图片。

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);  
                                });  

所以我想问一下如何才能完全等到图像存在于文件夹中才能共享 post 谢谢。

而不是

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,
  });

P.S。 : 尝试制作模块化代码,