JS:承诺不返回值 [英] JS: Promise doesn't return value
问题描述
我需要获取异步函数的值.我尝试使用 Promise,但这不起作用:
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)
我得到的结果是 Promise { <pending>}
推荐答案
Promise 是回调的抽象,而不是魔法.他们无法使异步代码同步.
Promises are an abstraction for callbacks, not magic. They can't make asynchronous code synchronous.
正确的解决方法是:
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)
})
您也可以在此处使用 async/await
:
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)}`);
}
或者,如果您使用的是 NodeJS(版本 8+),您或许可以调整您的函数以使用 util.promisify
.
其他 Promise
库,例如 Bluebird
,也提供了这样的函数,可以轻松地转换标准"节点样式的函数(具有 err、data
作为参数)转换为承诺返回的等价物.
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.
或者只是使用回调.
这篇关于JS:承诺不返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!