在承诺函数之前链Javascript函数只能基于初始函数调用

时间:2018-01-12 18:55:00

标签: javascript asynchronous promise async-await es6-promise

考虑以下正常工作的代码(下面的函数通常在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的函数,如下所示?< / p>

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实现这样的东西。

&#13;
&#13;
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');
});
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

在您的示例中,您只需将函数引用传递给then方法:

isAlive().then(getNetworks).then( result => {
    console.log( 'GET NETWORKS', result );
}).catch( error => {
    console.log( 'GET NETWORKS ERROR', error.message );
});

尝试避免嵌套的承诺确实是一种好习惯,而是将每个承诺返回到外部承诺链。

答案 1 :(得分:0)

您可以在Promise原型上定义方法,但您需要在方法中使用.then()

Promise.prototype.getNetworks = function(value) {
  // do stuff
  return this.then(function(data) {
    // do stuff
    return data
  })
  .catch(function(err) {
    throw err
  })
};

然后你可以使用模式

isAlive().getNetworks();

答案 2 :(得分:0)

看看这是否有帮助

async function myFunc() {
throw new Error("Whoops!");
}

在调用中,您可以捕获错误(拒绝)

myFunc()
.catch(function(rej, resolve)
   {console.log(`in the catch block rej ${rej}`
)});
相关问题