Javascript 节点从嵌套承诺返回数据
我对承诺是相当陌生的,因此我可以对如何让它发挥作用提出任何建议。 我尝试的所有变体都没有成功触发最终的成功/错误回调,或者成功触发但没有返回数据Javascript 节点从嵌套承诺返回数据,javascript,node.js,es6-promise,Javascript,Node.js,Es6 Promise,我对承诺是相当陌生的,因此我可以对如何让它发挥作用提出任何建议。 我尝试的所有变体都没有成功触发最终的成功/错误回调,或者成功触发但没有返回数据 export function getData(start, end, tagSet){ let data = new dataSet(); // Initial setup to work out what data to fetch return database.Read(config).then(function (r
export function getData(start, end, tagSet){
let data = new dataSet();
// Initial setup to work out what data to fetch
return database.Read(config).then(function (results) {
// Process the results.......
return data;
}, function (errCode) {
// Throw Error
});
}
// Call the function, triggered by a seperate event
getData.then(function(data){
//Success !!
},function(err){
//Failure!!
});
我也试着建立一个新的承诺
export function getData(start, end, tagSet){
let data = new dataSet();
// Initial setup to work out what data to fetch
return new Promise(function(resolve, reject) {
database.Read(config).then(function (results) {
// Process the results.......
// Update data
}, function (errCode) {
// Throw Error
});
return data;
}
}
我不想使用wait阻塞getData函数,那么从函数中的承诺返回数据的正确方法是什么呢
- 编辑:打字错误
- 看起来我误解了await在异步指令中的工作原理
export function getData(start, end, tagSet){
let data = new dataSet();
// Initial setup to work out what data to fetch
return new Promise(function(resolve, reject) {
database.Read(config).then(function (results) {
// Process the results.......
// Update data
}, function (errCode) {
// Throw Error
reject(errCode) // <-- if error happens, you reject your promise with error
});
resolve(data) // <<-- if there is no error, you resolve your data
}
}
看起来我想要的解决方案是将函数设置为异步并使用等待
export async function getData(start, end, tagSet){
let data = new dataSet();
// Initial setup to work out what data to fetch
await database.Read(config).then(function (results) {
// Process the results.......
// update data
}, function (errCode) {
// Throw Error
});
return data;
}
// Call the function, triggered by a seperate event
getData().then(function(data){
// Success !!
// data has been completed here
},function(err){
// Failure!!
});
这将导致返回的数据在成为getData()之前完成。然后()被触发。
getData。然后(…)
您需要调用getDatagetData(开始、结束、标记集)。然后(…)
抱歉,这是问题中的一个输入错误-实际的代码确实有这个错误-我只是在简化问题时不小心弄错了。然后错误必须出现在代码中的某个地方,您删除了该代码以简化代码,因为您的第一个代码段基本上应该可以工作。感谢您的帮助-解析看起来正是我想要的,但是我已经尝试了您建议的代码,并且getData承诺正在数据库运行之前解析。Read()。then()已运行。否。首先,在您的示例中,resolve(data)
在database.Read(config)
完成之前被调用。它不会等待处理结果,也不会等待查看是否发生错误。它将始终并立即解析(数据)
。其次,整个方法是一种反模式。无需创建新承诺
,因为database.Read(config)
已返回承诺。
export async function getData(start, end, tagSet){
let data = new dataSet();
// Initial setup to work out what data to fetch
await database.Read(config).then(function (results) {
// Process the results.......
// update data
}, function (errCode) {
// Throw Error
});
return data;
}
// Call the function, triggered by a seperate event
getData().then(function(data){
// Success !!
// data has been completed here
},function(err){
// Failure!!
});