简体   繁体   中英

How to make call to a JavaScript promise cleaner?

I have the following call to a Javascript promise:

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

It works fine, but it looks really wordy. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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