我有以下代码
async function callme(){
methods.callfun(x)
.then(function (res) {
methods.callfunxx(res)
.on("send", function (r) {
console.log(r);
})
.on("error", function (error, r) {
console.error(error);
});
});
}
我想这样打电话
const rr = await callme();
但它没有等待,所以我正在尝试在等待中更改它并在下面尝试
async function callme(){
const res = await methods.callfun(x);
const response = await methods.callfunxx(res)
response.on('send',() => {
return (`Successfully`)
});
response.on('error',() => {
return (`error`)
});
}
直到第二秒等待它的等待......但休息没有按预期工作......我正在尝试根据发送/错误返回响应。
任何帮助
谢谢
您当前的尝试根本不使用 promise,它只返回一个字符串。
response.on('send', () => {
return (`Successfully`) // string was returned, but nothing happened afterwards
});
您的函数已经是异步的,如async function
中的async
所示。 您已经可以这样称呼它:
const rr = await callme();
它返回一个解析为undefined
的承诺。
要使其返回一个Promise
,该 使用methods.callfunxx
返回的值解析/拒绝,您需要使用Promise
构造函数,在事件完成或发生错误时调用resolve
/reject
。
function callme() {
const res = await methods.callfun(x);
const ret_value = methods.callfunxx(res);
return new Promise(
(resolve, reject) => {
ret_value.on("send", resolve).on("error", reject);
}
);
};