skip to Main Content

I know this has been asked multiple times. And I’ve been through many of the answers. But no answer did work for me. Code was running and didn’t wait for the callback / promise resolve etc. Or it was waiting forever for the callback.

So I have a function that calles an asynchronous function Files.load() with a callback and Files.load() doesn’t return a promise:

function loadfile(url) {
  ...

  Files.load(url),options, (error, file) => {
    if (error) {
      throw error;
    } else {
      return file;
    }
  }
}

So i tried to build a promise wrapper;

function loadFileWrapper(url) {
  return new Promise((resolve, reject) => {
    loadFile(fileObj, (successResponse) => {
      resolve(successResponse); // this was never executed
    }, (errorResponse) => {
      reject(errorResponse); // neither this
    });
  });
}

And called it in an async funtion

async function fileParsing() {
  const file = await loadFileWrapper(file);
  // code here should wait after loadFileWrapper returns a value?
}

Can someone help me, what I’m doing wrong?

2

Answers


  1. So i tried to build a promise wrapper

    loadFile(fileObj, (successResponse) => {
    

    Now you are passing two arguments to loadFile, but loadFile only takes one argument.

    You need to wrap Files.load (i.e. the function which actually performs the asynchronous operation and which accepts a callback) with a promise, not loadFile.


    function loadfile(url) {
      return new Promise((resolve, reject) => {
        Files.load(url ,options, (error, file) => {
          if (error) {
            return reject(error);
          } else {
            return resolve(file);
          }
        }
      };
    }
    
    Login or Signup to reply.
  2. You can solve this with 2 approaches, I personally prefer a promise-based approach because we can use async/await.

    add a callback to loadfile function

    function loadfile(url, cb) {
      // ...
      Files.load(url, options, cb);
    }
    

    Promise approach

    function loadfile(url) {
      return new Promise((resolve, reject) => {
        Files.load(url, options, (error, file) => {
          if (error) {
            reject(error);
          } else {
            resolve(file);
          }
        });
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search