-1

hello all I have some problems with my async function the test will be undefined what am I doing wrong I need help with this it's so frustrating

async function fileToObj(jsonOfXls){
    const promises = jsonOfXls.Blad1.map(async x => {
      let test;
      await base64.encode(`pdfs/${x.E}`,  function (err, base64String) {
        test = base64String
      })
      return { gtin: x.D, gln: x.C, order: x.B, file: test }
    })
    const output = await Promise.all(promises)
   console.log(output)
}

i try now this :

async function fileToObj(jsonOfXls) {
  const output = await Promise.all(
    jsonOfXls.Blad1.map(async x => {
      const file = await new Promise((resolve, reject) => {
        base64.encode(`pdfs/${x.E}`, function(err, base64String) {
          if (err != null) {
            return reject(err)
          }
          resolve(base64String)
        })
      })
      return { gtin: x.D, gln: x.C, order: x.B, file }
    })
  )
  console.log(output)
}

but i get this error:

72) UnhandledPromiseRejectionWarning: encode fail (node:8772) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (reject ion id: 1)

  • The way you call `base64.encode` looks like you mix both styles, i.e. you still have the callback there. I'd remove the callback, i.e. I would replace this whole line with `let test = await base64.encode(`pdfs/${x.E}`);`. This of course works only if the api returns a promise. – Wiktor Zychla Feb 12 '20 at 10:28

1 Answers1

1

You can only usefully await a promise.

base64.encode takes a callback which implies it doesn't return a promise.

Awaiting its return value therefore has no practical effect.

You would need to wrap it in a promise before you can await it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • i try now this : ```js async function fileToObj(jsonOfXls) { const output = await Promise.all( jsonOfXls.Blad1.map(async x => { const file = await new Promise((resolve, reject) => { base64.encode(`pdfs/${x.E}`, function(err, base64String) { if (err != null) { return reject(err) } resolve(base64String) }) }) return { gtin: x.D, gln: x.C, order: x.B, file } }) ) console.log(output) } ``` – Dyon van Gerwen Feb 12 '20 at 11:16