【问题标题】:Chain Javascript function before promise function to only call based on initial function在 Promise 函数之前链 Javascript 函数仅基于初始函数调用
【发布时间】: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


【解决方案1】:

看看有没有帮助

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

在调用这里,你可以捕获错误(reject)

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

【讨论】:

    【解决方案2】:

    您可以在 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();
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

      • 另外值得注意的是isAlive() 的编码方式,它从不拒绝,因此从不使用.catch()。但是,isAlive() 的写法可能是个错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 2011-05-02
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多