[英]Await for function that returns promise when event occurs
I'm reading post data with a function, when it reads all data on "end" it returns a promise, the problem is that when it returns the promise the function doesn't resume. 我正在使用函数读取发布数据,当它读取“ end”上的所有数据时会返回一个Promise,问题是当它返回Promise时该函数不会恢复。 This is the code: 这是代码:
if (true) {
log.check(ip, async function (c) {
if (c) {
const data = await ReadPost(req).catch(function (err) {
console.error(err);
});
console.log("Error:m" + data);
}
});
}
function ReadPost(req) {
var data = "";
if (req.method === 'POST') {
req.on('data', function (buffer) {
data += buffer;
});
req.on('end', function () {
data = data.toString();
console.log("Data:" + data);
return Promise.resolve(data);
});
}
else {
return Promise.reject();
}
}
} }
I don't know if its possible to do it that way, to solve this I would put the rest of the function below the await inside req.on end, also is possible for req.on end to be called twise? 我不知道是否有可能这样做,要解决这个问题,我会将其余功能放在req.on end内部的await之下,也可能将req.on end称为twise吗?
The function doesn't actually return a Promise, it returns undefined
, or rejects a Promise. 该函数实际上并不返回Promise,而是返回undefined
,或拒绝Promise。 To make it work with await, you have to return a Promise at the top of the function, and then call resolve
in the onend listener: 要使其与await一起使用,您必须在函数顶部返回一个Promise,然后在onend侦听器中调用resolve
:
function ReadPost(req) {
return new Promise((resolve, reject) => {
var data = "";
if (req.method === 'POST') {
req.on('data', function(buffer) {
data += buffer;
});
req.on('end', function() {
data = data.toString();
console.log("Data:" + data);
resolve(data);
});
} else {
reject();
}
});
}
Here the function returns a Promise right away before listening to the end, or data listeners. 在这里,该函数会在侦听结尾或数据侦听器之前立即返回一个Promise。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.