JS: Promise doesn't return value

末鹿安然 提交于 2019-12-02 13:55:27

问题


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> }


回答1:


Promises are an abstraction for callbacks, not magic. They can't make asynchronous code synchronous.

The correct solution is:

const res = new Promise(function (resolve, reject) {
  gm(readStream).size({ bufferStream: true }, function (err, size) {
    if (err) reject(err);
    else resolve(size);

  })
});

res.then(function(promiseResolutionValue) {
    console.log(res)
})

You could also use async / await here:

const getSize = readStream => {
    return new Promise(function (resolve, reject) {
    gm(readStream).size({ bufferStream: true }, function (err, size) {
      if (err) reject(err);
      else resolve(size);
    })
  });
}


let printSize = async readStream => {
  console.log(`Size is ${await getSize(readStream)}`);
}

Or, if you're using NodeJS (Version 8+), you might be able to adapt your function to use util.promisify.
Other Promise libraries, such as Bluebird, also offer such functions, to easily convert 'standard' node-style functions (functions that have a callback with err, data as arguments) into promise-returning equivalents.

Or just use the callback.




回答2:


Your code should be looked like this:

const res = new Promise(function (resolve, reject) {
  gm(readStream).size({ bufferStream: true }, function (err, size) {
    if (!err) resolve(size)
    else reject(err)
  })
})

function onResolved(data) {
  console.log('data: ', data);
}

function onRejected(err) {
  console.log('err:', err);
}

res.then(onResolved, onRejected);

Promise does not make your code synchronous, it lets you control when you want to get the result, not immediately like callback style.



来源:https://stackoverflow.com/questions/46120825/js-promise-doesnt-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!