我是 nodejs 的新手,它是回调 hell ,我在 Node 8 中阅读了有关 async/await 的介绍,并且有兴趣以这种方式实现它
我有一组特定的方法,我需要以同步方式一个接一个地为 trello API 调用 例如
你可以想象在 nodejs 中,这需要大量的回调嵌套到另一个中以访问前一个对象
createProjectBoard: function (project) {
t.post("1/board", {
name: project.name,
desc: project.description,
defaultLists: false
}, function (err, board) {
if (err) {
console.log(err);
throw err;
}
//get board id from data
let boardId = board.id
let backlogListId = "";
let highId = "", mediumId = "", lowId = "";
//create labels
t.post("1/labels", {
name: 'High',
color: 'red',
idBoard: boardId
}, function (err, label) {
console.log(err || 'High label created');
if (err) return;
highId = label.id;
});
t.post("1/labels", {
name: 'Medium',
color: 'orange',
idBoard: boardId
}, function (err, label) {
console.log(err || 'Medium label created');
if (err) return;
mediumId = label.id;
});
t.post("1/labels", {
name: 'Low',
color: 'yellow',
idBoard: boardId
}, function (err, label) {
console.log(err || 'Low label created');
if (err) return;
lowId = label.id;
});
//create rest of the lists
t.post("1/lists", { name: "Completed", idBoard: boardId }, function (e, l) {
if (e) {
console.log(e);
return;
}
console.log(l);
t.post("1/lists", { name: "Testing", idBoard: boardId }, function (e, l) {
if (e) {
console.log(e);
return;
}
console.log(l);
t.post("1/lists", { name: "In Progress", idBoard: boardId }, function (e, l) {
if (e) {
console.log(e);
return;
}
console.log(l);
//create backlog list
t.post("1/lists", { name: "Backlog", idBoard: boardId }, function (e, list) {
if (e) {
console.log(e);
return;
}
console.log(list);
backlogListId = list.id;
console.log("backlog card list id:" + backlogListId);
_.each(project.userStories, function (story) {
//assign labels
let labelId = "";
switch (story.complexity.toLowerCase()) {
case 'high':
labelId = highId;
break;
case 'medium':
labelId = mediumId;
break;
default:
labelId = lowId;
}
t.post("1/cards", {
name: story.title,
idLabels: labelId,
idList: backlogListId
}, function (e, card) {
if (e) {
console.log(e);
return;
}
let cardId = card.id;
console.log("created id:" + cardId + ";card:" + story.title);
t.post("1/cards/" + cardId + "/checklists", {
name: "Acceptance Criteria"
}, function (e, checklist) {
if (e) {
console.log(e);
return;
}
console.log('checklist created:');
var clId = checklist.id;
_.each(story.criterion, function (criteria) {
t.post("1/cards/" + cardId + "/checklist/" + clId + "/checkItem", {
name: criteria
}, function (e, checkItem) {
if (e) {
console.log(e);
return;
}
console.log('created check item:' + checkItem);
});
});
});
});
});
});
});
});
});
});
}
我仍然对上面的代码有问题,其中涉及 __.each 循环,它异步调用循环中的所有函数(重新安排它们最初应该在的项目的顺序) - 所以我认为必须有更好的方法来同步调用
我对使用 await/async 清理代码很感兴趣,但是在从异步回调返回对象时遇到了一些麻烦
解决方案基于sails.js,以下是我写的TrelloService的节选
考虑以下几点:
createProjectBoard: async function(project) {
//get board id from data
let board;
let boardId = "";
let backlogListId = "";
let highId = "",
mediumId = "",
lowId = "";
try {
await t.post("1/board", {
name: project.name,
desc: project.description,
defaultLists: false
},
function(err, b) {
if (err) {
console.log(err);
throw err;
}
console.log("board" + b);
board = b;
});
//create labels
await t.post("1/labels", {
name: 'High',
color: 'red',
idBoard: board.id
}, function(err, label) {
console.log(err || 'High label created');
if (err) return;
highId = label.id;
});
} catch (err) {
console.log(err);
}
}
我需要 board 值在标签请求调用中可用,到目前为止我无法检索 board 对象、事件,尽管我已经设置了等待关键字
我需要能够从回调函数中获取对象并以同步方式将它们用于后续函数调用
我正在使用 trello api 包装器 node-trello 进行调用 (t)
一种方法是将上面的函数包装在更多函数中,如下所示,但我认为这不是最佳实践,因为我必须在我需要使用的每个对象上编写包装器回调
function foo(url,options,cb){
await t.post(url, options,
function(err, b) {
if (err) {
console.log(err);
throw err;
}
console.log("board" + b);
cb(b);
});
}
var url = "1/board";
var options = {
name: project.name,
desc: project.description,
defaultLists: false
};
foo(url,options,function(board){
console.log(board); //board object
});
感谢任何建议
最佳答案
I'm interested in using await / async to clean out the code
这有两个步骤:promisification 和 async。您的代码越来越困惑,因为它跳过了第一步。
Promisification 在回调函数周围创建非常简单的返回 promise 的包装函数。例如,如果 t 是 Trello 类的实例:
Trello.prototype.postAsync = (url, data) => new Promise((resolve, reject) => {
this.post(url, data, (err, result) => {
if (err) { reject(err); }
else { resolve(result); }
});
});
第二 步是编写您的async/await 逻辑,使用 promise 返回函数而不是回调。由于它们是 promise 返回的,因此它们的代码更加自然:
const board = await t.postAsync("1/board", {
name: project.name,
desc: project.description,
defaultLists: false
});
console.log("board" + board);
//create labels
let highId;
try {
highId = await t.postAsync("1/labels", {
name: 'High',
color: 'red',
idBoard: board.id
});
} catch (err) {
console.log(err || 'High label created');
return;
}
promisification 步骤是乏味和重复的。有一些库可以自动回调到 promise ,最著名的是 Bluebird .
关于javascript - 如何使用回调函数的异步等待从异步函数返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45351623/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
很好奇,就使用rubyonrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提
假设我做了一个模块如下:m=Module.newdoclassCendend三个问题:除了对m的引用之外,还有什么方法可以访问C和m中的其他内容?我可以在创建匿名模块后为其命名吗(就像我输入“module...”一样)?如何在使用完匿名模块后将其删除,使其定义的常量不再存在? 最佳答案 三个答案:是的,使用ObjectSpace.此代码使c引用你的类(class)C不引用m:c=nilObjectSpace.each_object{|obj|c=objif(Class===objandobj.name=~/::C$/)}当然这取决于
我正在尝试使用ruby和Savon来使用网络服务。测试服务为http://www.webservicex.net/WS/WSDetails.aspx?WSID=9&CATID=2require'rubygems'require'savon'client=Savon::Client.new"http://www.webservicex.net/stockquote.asmx?WSDL"client.get_quotedo|soap|soap.body={:symbol=>"AAPL"}end返回SOAP异常。检查soap信封,在我看来soap请求没有正确的命名空间。任何人都可以建议我
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t