D
D
Dmitry Sch2021-07-22 18:03:21
Node.js
Dmitry Sch, 2021-07-22 18:03:21

How to wait for the code in a Promise to execute to resolve()?

Task: Read the content of the file, convert it to Base64 and send it to the server.

When in the Promise on the callback of reading the file I do resolve() with the conversion of the file to Base64, apparently it works before the file is converted (it seems due to the file size) and an empty string is sent to the server.
How to get around this, you need to exactly wait for the conversion and only then execute resolve().

Third party plugins from npm don't have cb either after converting to string
https://www.npmjs.com/package/nodejs-base64

function uploadFile(event, cb){
  const file = event;
  const fileName = path.basename(file);

  new Promise((resolve) => {
    fs.readFile(`${file}`, {encoding: 'utf8'}, (err, data) =>{
      if (err) throw err;
      resolve(Buffer.from(data).toString('base64')) // Как здесь дождаться конвертации в BASE64
    });
  })
  .then((encoded) => {		
    const params = new URLSearchParams();
    params.append('secret_key', SECRET_KEY);
    params.append('form[file_name]', `${fileName}`);
    params.append('form[file_content]', `${encoded}`);
    
    fetch(href, {
      method: 'post',
      body:    params,
      timeout: 5000,
    })
    .then(res => res.json())
    .then(json=>{
      if(json.status === `ok`){}
    })
  })
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2021-07-22
@Fragster

Starting from node 10, there is a file api not on callbacks, but on promises, why not use it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question