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
Now you are passing two arguments to
loadFile
, butloadFile
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, notloadFile
.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
Promise approach