简体   繁体   English

如何调用JavaScript Promise清洁程序?

[英]How to make call to a JavaScript promise cleaner?

I have the following call to a Javascript promise: 我对Javascript Promise进行了以下调用:

deleteDatabase().then(function () {
    doSomeStuff();
}, function (err) {
    processError(err);
});

It works fine, but it looks really wordy. 它工作正常,但看起来确实很罗word。 Is there a way to have a terser way to do this? 有没有办法做到这一点? Maybe something like this (which does not seem to work): 也许是这样的(似乎不起作用):

deleteDatabase().then(doSomeStuff(), processError(err));

You need to pass a function , not the result of calling them: 您需要传递一个函数 ,而不是调用它们的结果:

deleteDatabase().then(doSomeStuff, processError);

Of course, this will pass the result of the deleteDatabase() action to your doSomeStuff function, so if you expect it to get no arguments you will need to use the function expression as you did. 当然,这会将deleteDatabase()操作的结果传递给doSomeStuff函数,因此,如果希望它不获取任何参数,则需要像以前一样使用函数表达式。

You have an issue with the syntax 您的语法有问题

deleteDatabase().then(doSomeStuff, processError);

if you put () after the function name it will call it immediately, by omitting the parenthesis you are passing a reference to the function and asking for it to be called at some point later on by the promise. 如果将()放在函数名称之后,它将立即调用它,通过省略括号,您将传递对该函数的引用,并要求在以后的某个时刻调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM