【发布时间】:2018-06-22 06:41:54
【问题描述】:
考虑以下正常工作的代码(下面的函数通常在API 对象内):
let Query = async function( method, endpoint, options, successCode, obKey ){
return true;
//return new Error( 'Could not complete query!' );
};
let isAlive = async function( options ){
try {
return await Query( 'GET', '/heart', options, 204 );
} catch( error ){
return error;
}
};
let getNetworks = async function(options) {
try {
return await Query( 'GET', '/networks', options, 200, 'networks' );
} catch( error ){
return error;
}
};
// Standard promise method works
isAlive().then( () => {
getNetworks().then( result => {
console.log( 'GET NETWORKS', result );
}).catch( error => {
console.log( 'GET NETWORKS ERROR', error.message );
});
}
);
// BUT to make for cleaner code base, how can I only call next function in chain
// based on isAlive() function?
如何处理isAlive() 函数以允许链接,但仅执行基于isAlive() 之后基于isAlive() 中的结果调用的基于Promise 的函数,如下所示?
isAlive().getNetworks().then( result => {
console.log( 'GET HOMIE NETWORKS', result );
}).catch( error => {
console.log( 'GET HOMIE NETWORKS ERROR', error.message );
});
是的,我知道可以从async 函数内部以这种方式完成,但是,有时await isAlive(); 是不可能的......并且希望能够创建一个简单的辅助函数可以链接到...这可能吗?不用.then( ()=> { ... } )?
Glot.IO:https://glot.io/snippets/exas8rbxyu JSFiddle:https://jsfiddle.net/tripflex/sj78297k/
我能够通过返回 this 找出一些基本的链接,但不知道如何使用 Promises 实现类似的东西。
var myObj = {
hasPerms: false,
check : function( doChain ){
this.hasPerms = doChain;
console.log( 'Checkinnngggg...' );
return this;
},
then : function( callback ){
if( this.hasPerms ){
callback();
} else {
return false;
}
}
};
//"chain, chain, chain..."
myObj.check( false ).then( function(){
console.log( 'I GOT FOO\'D');
});
【问题讨论】:
-
return await fn()永远不需要。只需return fn()。
标签: javascript asynchronous promise async-await es6-promise