1

我有一系列的事件是这样的:

//Download a file and write it to disk
await downloadSyncFile(user, downloadURL)
//Use the file...
await useTheFile() //Crash! The file is only partially there! Dangit!

在文件实际在磁盘上之前,我的代码会继续运行。这是我的下载功能:

async function downloadSyncFile(user, downloadURL){
  //Setup download path
  let path = './data/'+user+'/file.whatevs'

  try{
    //Download and save file
    let stream = fs.createWriteStream(path)
    let response = await axios.get(downloadURL, { responseType: 'stream' })
    response.data.pipe(stream)

    await new Promise(fulfill => stream.on('finish', fulfill))


  }catch(error){
    console.log('downloadSyncFile Error: '+error)
    return { success: false, message: error }
  }
}

下载完成downloadSyncFile()后,该功能似乎正在返回axios,但未完成对磁盘的写入。

如何确保文件在downloadSyncFile()返回之前安全地写入磁盘?

4

1 回答 1

1

您不会从downloadSyncFile().

改变

await new Promise(fulfill => stream.on('finish', fulfill));

return new Promise(fulfill => stream.on('finish', fulfill));

最好这样写:

async function downloadSyncFile(user, downloadURL) {
    return new Promise((fulfill, reject) => {
        let path = './data/' + user + '/file.whatevs';
        let stream = fs.createWriteStream(path);
        let response = await axios.get(downloadURL, { responseType: 'stream' });
        response.data.pipe(stream);
        stream.on('finish', fulfill));
        stream.on('error', reject); // presumably
    });
}

将所有内容都包含在new Promise(...),try{} catch() {}中是不必要的,因为任何同步错误都会导致 Promise 被拒绝。

于 2020-04-16T08:29:54.527 回答