如何实现此功能 - nodejs [英] How to Promisify this function - nodejs
本文介绍了如何实现此功能 - nodejs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个需要返回承诺的ajax调用。功能如下
I have an ajax call which needs to return a promise. The function is as follows
client.tickets.create(ticket, function(err, req, result) {
if (err) {
logger.error(err);
return false;
}
return JSON.stringify(result);
});
我必须等待此功能执行才能执行下一个操作。我怎样才能宣传这个功能?
I have to wait for this function to execute before I can perform the next action. How can I promisify this function ?
我尝试了以下内容并且它给了我一个错误说无法调用方法然后是未定义的
:
I tried the following and it gave me an error saying Cannot call method then of undefined
:
return client.tickets.create(ticket).then(function(result){
return JSON.stringify(result);
},function(err){
logger.error(err);
return false;
});
推荐答案
您有错误,因为 create()
不是Promise。宣传异步功能非常简单(nodejs现在有内置的Promise支持):
You have the error because create()
is not a Promise. Promisifying an async function is quite easy (nodejs has a built-in Promise support nowadays):
function createTicket(ticket) {
// 1 - Create a new Promise
return new Promise(function (resolve, reject) {
// 2 - Copy-paste your code inside this function
client.tickets.create(ticket, function (err, req, result) {
// 3 - in your async function's callback
// replace return by reject (for the errors) and resolve (for the results)
if (err) {
reject(err);
} else {
resolve(JSON.stringify(result));
}
});
});
}
// 4 - consume your promise with then() (resolved promise) and catch (rejected promise)
createTicket(ticket).then(function (result) {
// deal with result here
}).catch(function (err) {
// deal with error here
});
这篇关于如何实现此功能 - nodejs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文