I need to get a value of an asynchronous function. I tried to use Promise, but that does not work:
const res = new Promise(function (resolve, reject) {
gm(readStream).size({ bufferStream: true }, function (err, size) {
if (!err) resolve(size)
})
})
console.log(res)
The result I get is Promise { <pending> }
Promises are an abstraction for callbacks, not magic. They can't make asynchronous code synchronous.
The correct solution is:
You could also use
async / await
here:Or, if you're using NodeJS (Version 8+), you might be able to adapt your function to use
util.promisify
.Other
Promise
libraries, such asBluebird
, also offer such functions, to easily convert 'standard' node-style functions (functions that have a callback witherr, data
as arguments) into promise-returning equivalents.Or just use the callback.